开发者

Packing 4 bytes into an int [duplicate]

This question already has answers here: Closed 11 years ago.

Poss开发者_如何学JAVAible 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.


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.


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.


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);


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜