将 4 个字节打包成一个 int
可能的重复:
将 4 个字节转换为 int
我正在尝试使用一些方法将 4 个字节打包为 int此处找到的解决方案之一,但它似乎不适用于我的一项测试。
这是我正在使用的代码:
public static int pack(int c1, int c2, int c3, int c4)
{
return (c1 << 24) | (c2 << 16) | (c3 << 8) | (c4);
}
现在,当我在 0x34、0x68、0x77 和 0x23 等简单的东西上使用它时,我得到了我所期望的:0x34687723。但当我在 0xBA、0xAD、0xBE 和 0xEF 上使用它时,我得到了一些东西。有人看出可能是什么问题吗?
编辑
上面的代码能够给我我想要的东西,我下面提到的“错误值”只是以十进制形式表示 0xBAADBEEF 的另一种方式。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
pack 方法中的代码是正确的并保留所有位,但由于结果存储在有符号 int 中,当您尝试将其打印为 int 或进行算术计算或与之比较时,您会得到错误的结果。
这会将 int 打印为无符号 int。
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.
This prints the int as a unsigned int.
存储在 Java
int
中的数字只能表示0x7fffffff
以内的正值(2147483647、Integer.MAX_VALUE
),因为它是有符号类型 (像所有 Java 数字类型一样),并且在内部表示中最高有效位用作符号位。要保存大于该值的正数值,您需要使用
long
来代替:请注意末尾的显式
long
掩码操作,这是确保符号扩展不会发生的必要条件。导致负整数结果被转换为负长整型。A number stored in a Java
int
can only represent positive values up to0x7fffffff
(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: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.标志扩展。在 Java 中,整数是有符号的,所以 0xBA<<24 会不高兴。我建议您将其打包到
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
.你得到的是负数吗?也许无符号整数或更长的整数会更好。
Are you getting a negative number? Perhaps an unsigned int or a longer int would work better.