包装4个字节为一个int

包装4个字节为一个int

本文介绍了包装4个字节为一个int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  

我想装4字节到使用一些在这里找到解决方案的一个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.

这是code我使用的是:

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

现在,当我使用它像0x34,为0x68,0x77,0x23和简单的东西,我得到我所期望的:0x34687723。但是,当我使用它0xBA,写入0xAD,0xBE和0xEF我得到的东西的路要走。有没有人看到这个问题可能是什么?

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?

修改

以上code是能够给我我想要的东西,而错误值下面我提的是另一个以小数形式重新presenting 0xBAADBEEF方式。

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.

推荐答案

存储在Java INT A数只能重新present正值可达为0x7FFFFFFF (2147483647 Integer.MAX_VALUE的),因为它是一个符号类型(如所有Java数字类型),并在内部重新presentation最显著位被用作符号位。

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.

这篇关于包装4个字节为一个int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 01:53