最近我问了一个问题:Replace byte in a int
这显示了如何替换整数上的字节。我也需要对 Int64 做同样的事情。显然我不擅长这个哈哈。我不知道为什么将 int 替换为 Int64 不能使其工作。换句话说,我将最后一个问题的解决方案修改为:
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 );
}
这在使用大值时不起作用。例如将方法调用为:
// 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 );
我怎样才能让它也与 Int64 一起工作?我究竟做错了什么?唯一有效的方法是最后一种最慢的方法。
编辑
我已经做了替换,但我仍然得到不同的结果。为什么?看一看:
// 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( );
}