Packing 4 bytes into an int [duplicate]

泄露秘密 提交于 2019-12-14 02:57:10

问题


Possible Duplicate:
Convert 4 bytes to int

I'm trying to pack 4 bytes into an int using some of the solutions found here, but it doesn't seem to work for one of my tests.

This is the code I'm using:

public static int pack(int c1, int c2, int c3, int c4)
{
    return (c1 << 24) | (c2 << 16) | (c3 << 8) | (c4);
}

Now when I use it on something simple like 0x34, 0x68, 0x77, and 0x23 I get what I expect: 0x34687723. But when I use it on 0xBA, 0xAD, 0xBE, and 0xEF I get something way off. Does anyone see what the problem might be?

EDIT

The above code was able to give me what I wanted, and the "wrong value" I mention below is just another way of representing 0xBAADBEEF in a decimal form.


回答1:


A number stored in a Java int can only represent positive values up to 0x7fffffff (2147483647, Integer.MAX_VALUE), as it's a signed type (like all Java number types), and in the internal representation the most significant bit is used as a sign bit.

To hold positive numeric values larger than that you need to use a long instead:

public static long pack(int c1, int c2, int c3, int c4)
{
        return ((c1 << 24) | (c2 << 16) | (c3 << 8) | (c4)) & 0xffffffffL;
}

Note the explicit long mask operation at the end which is necessary to ensure that sign extension doesn't cause a negative integer result from being turned into a negative long.




回答2:


Your code in the pack method is correct and preserves all bits but since the result is stored in a signed int you get a wrong result when you try to print it as an int or when you do arithmetic calculations or comparisons with it.

int result = pack( c1, c2, c3, c4 );
System.out.println( "result=" + Long.toHexString( result & 0xffffffffL );

This prints the int as a unsigned int.




回答3:


Sign extension. In Java ints are signed, so 0xBA<<24 gets unhappy. I suggest that you pack into the last four bytes of a long.

long temp =
   ((0xFF & c1) << 24) | ((0xFF & c2) << 16) | ((0xFF & c3) << 8) | (0xFF   & c4);

return (int)(temp & 0x0FFFFFFFFL);



回答4:


Are you getting a negative number? Perhaps an unsigned int or a longer int would work better.



来源:https://stackoverflow.com/questions/6117614/packing-4-bytes-into-an-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!