Recently I asked the question: Replace byte in a int
and that shows how to replace a byte on an integer. I need to do the same thing with Int64 too. Apparently I am to bad at this lol. I do not know why replacing int to Int64 does not make it work. In other words I modified the solutions on the last question to:
static Int64 ReplaceByte1( int index , Int64 value , byte replaceByte )
{
return ( value & ~( 0xFF << ( index * 8 ) ) ) | ( replaceByte << ( index * 8 ) );
}
static Int64 ReplaceByte2( int index , Int64 value , byte replaceByte )
{
// how many bits you should shift replaceByte to bring it "in position"
var shiftBits = 8 * index;
// bitwise AND this with value to clear the bits that should become replaceByte
Int64 mask = ~( 0xff << shiftBits );
// clear those bits and then set them to whatever replaceByte is
return value & mask | ( replaceByte << shiftBits );
}
that does not work when using large values. For example calling the method as:
// returns 12345678848 where it should return 3755744309
var test1 = ReplaceByte1( 4 , 12345678901 , 0 );
// returns 12345678848 where it should return 3755744309
var test2 = ReplaceByte2( 4 , 12345678901 , 0 );
how can I make it work with Int64 too? what am I doing wrong? The only method that works is the last one the slowest one.
Edit
I already made the replacements and I still get different results. Why? take a look:
// method that words
static Int64 SlowReplace ( int index , Int64 value , byte replaceByte )
{
var bytes = BitConverter.GetBytes( value );
bytes[ index ] = replaceByte;
return BitConverter.ToInt64( bytes , 0 );
}
static Int64 ReplaceByte1 ( int index , Int64 value , byte replaceByte )
{
return ( value & ~( (long)0xFF << ( index * 8 ) ) ) | ( replaceByte << ( index * 8 ) );
}
static Int64 ReplaceByte2 ( int index , Int64 value , byte replaceByte )
{
// how many bits you should shift replaceByte to bring it "in position"
var shiftBits = 8 * index;
// bitwise AND this with value to clear the bits that should become replaceByte
Int64 mask = ~( ( Int64 )0xff << shiftBits );
// clear those bits and then set them to whatever replaceByte is
return value & mask | ( replaceByte << shiftBits );
}
static void Main ( string[ ] args )
{
var a = SlowReplace( 4 , 12345678901 , 255 ); // 1098972404789 corect
var b = ReplaceByte1( 4 , 12345678901 , 255 ); // 3755744511 incorrect
var c = ReplaceByte2( 4 , 12345678901 , 255 ); // 3755744511 incorrect
Console.Read( );
}