简体   繁体   English

Java-将byte []转换为int而不给出结果

[英]Java - converting byte[] to int not giving result

I have a hexBinary of 4 bytes as follows: 我有一个4字节的hexBinary,如下所示:

FFFFFFC4

It should return something big but the following function just gives -60: 它应该返回较大的值,但以下函数仅给出-60:

public static int byteArrayToInt(byte[] b) 
    {
        return   b[3] & 0xFF |
                (b[2] & 0xFF) << 8 |
                (b[1] & 0xFF) << 16 |
                (b[0] & 0xFF) << 24;
    }

Why it doesn't work? 为什么不起作用? Am I doing something wrong? 难道我做错了什么?

The primitive type int is 32-bits long and the most significative bit is the sign. 原始类型int长度为32位,而最高位是符号。 The value FFFFFFC4 has the MSB set to 1 , which represents a negative number. FFFFFFC4的MSB设置为1 ,表示负数。

You can get "something big" by using long instead of int : 您可以使用long而不是int来获得“大事”:

public static long byteArrayToInt(byte[] b) 
{
    return  (((long) b[3]) & 0xFF) |
            (((long) b[2]) & 0xFF) << 8 |
            (((long) b[1]) & 0xFF) << 16 |
            (((long) b[0]) & 0xFF) << 24;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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