简体   繁体   中英

Bitwise shift and byte cast gives different results in Java and C#

I'm testing the following code in both C# and Java:

int lngCRC = 3012;
byte[] crc = new byte[2];
crc[0] = (byte)(lngCRC & 0xFF);
crc[1] = (byte)(lngCRC >> 8);

C# output is:

crc[0] = 196;  
crc[1] = 11;

Java output is:

crc[0] = -60;  
crc[1] = 11;

How can I get the same result in both languages?

Java bytes are signed (ie between -128 and 127). I guess in C# they are unsigned.

3012 in binary is 00001011 11000100 .

The higer byte is 11, no matter if it's treated as a signed or unsigned byte.

When you treat the low byte - 11000100 - as an unsigned byte, it's 196

When you treat it as a signed byte, it's -60.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM