包装4个字节为一个int

编程入门 行业动态 更新时间:2024-10-28 10:33:12
本文介绍了包装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

本文发布于:2023-11-10 09:15:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574968.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字节   int

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!