要conbine 2字节成短:寻找一种方式来conbine的0xA5,并为0x9c到0xa59c
/* combine 0xa5 and 0x9c to 0xa59c */
public class Unsigned
{
public static void main(String[] args)
{
byte a = (byte) 0xa5;
byte b = (byte) 0x9c;
//int c = ((a&0xff)*256)&0xffff+(b&0xff); // 0
//int c = a*256+b; // ffffa49c
int c = (int)a*256+(int)b; // ffffa49c
System.out.printf("%4x\n", c);
}
}
为什么他们都是不正确的?
====
的可行版本:
/* combine 0xa5 and 0x9c to 0xa59c */
public class Unsigned
{
public static void main(String[] args)
{
byte a = (byte) 0xa5;
byte b = (byte) 0x9c;
//int c = ((a&0xff)*256)&0xffff+(b&0xff); // 0
//int c = a*256+b; // ffffa49c
//int c = (a&0xff)*256+(b&0xff); // a59c
int c = ((a & 0xFF)<< 8) | (b & 0xFF); // a59c
System.out.printf("%4x\n", c);
}
}
什么你的意思是“不正确”吗?你期望发生什么?究竟发生了什么? – Jeffrey 2012-08-12 15:10:38