1

将 2 个字节组合成一个短字节:

/* 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);
    }
}
4

3 回答 3

3

您可能希望使用按位算术而不是乘法。并且为了避免符号扩展将字节转换为 int(两者都是有符号的),您可以为第一个最低有效位 8 位应用位掩码。在代码中:

int a_byte = ((int)a & 0xFF);
int b_byte = ((int)b & 0xFF);
int c = (a_byte << 8) | b_byte;

总和而不是按位或也可以在这里工作而不会产生任何后果。在这种情况下,也可以省略到 int 的显式转换。

回答实际问题:您插入的值实际上是负数(超过 0x7F)。两者都转换为整数的结果保持负号,这会将所有额外的 24 位设置为 1。这肯定会影响结果。

于 2012-08-12T15:13:13.890 回答
1

你需要做的是:

int c = ((a & 0xFF )<< 8) | (b & 0xFF);
于 2012-08-12T15:11:24.940 回答
1

System.out.printf("%x\n",(short)((a << 8) | (0xff & b)));

将其转换short为 2 个字节而不是ffffa59c

向左移动以保留 a5 和ORwith 0xff&b0xff9cOR您保留时就是这样a5

于 2012-08-12T15:24:22.257 回答