将整数转换为字节数组(Java)
将整数
转换为字节数组
的快速方法是什么?
例如 0xAABBCCDD => {AA、BB、CC、DD}
what's a fast way to convert an Integer
into a Byte Array
?
e.g. 0xAABBCCDD => {AA, BB, CC, DD}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
查看 ByteBuffer 类。
设置字节顺序可确保
result[0] == 0xAA
、result[1] == 0xBB
、result[2] == 0xCC
和结果[3] == 0xDD
。或者,您也可以手动完成:
ByteBuffer 类是为此类脏手任务而设计的。事实上,私有
java.nio.Bits
定义了ByteBuffer.putInt()
使用的这些辅助方法:Have a look at the ByteBuffer class.
Setting the byte order ensures that
result[0] == 0xAA
,result[1] == 0xBB
,result[2] == 0xCC
andresult[3] == 0xDD
.Or alternatively, you could do it manually:
The
ByteBuffer
class was designed for such dirty hands tasks though. In fact the privatejava.nio.Bits
defines these helper methods that are used byByteBuffer.putInt()
:使用
BigInteger
:使用
DataOutputStream
:使用
ByteBuffer
:Using
BigInteger
:Using
DataOutputStream
:Using
ByteBuffer
:使用这个函数它对我有用
它将 int 转换为字节值
use this function it works for me
it translates the int into a byte value
如果您喜欢 Guava,您可以使用它的
Ints
类:对于
int
→byte[]
,使用toByteArray()
:结果为
{0xAA, 0xBB, 0xCC, 0xDD}
。其反向是 < code>fromByteArray() 或
fromBytes()
:结果为
0xAABBCCDD
。If you like Guava, you may use its
Ints
class:For
int
→byte[]
, usetoByteArray()
:Result is
{0xAA, 0xBB, 0xCC, 0xDD}
.Its reverse is
fromByteArray()
orfromBytes()
:Result is
0xAABBCCDD
.您可以使用 BigInteger:
来自整数:
返回的数组具有表示数字所需的大小,因此它的大小可以是 1,例如表示 1。但是,如果传递 int,则大小不能超过 4 个字节。
来自字符串:
但是,您需要注意,如果第一个字节高于
0x7F
(如本例所示),BigInteger 会在数组的开头插入一个 0x00 字节。这是区分正值和负值所必需的。You can use
BigInteger
:From Integers:
The returned array is of the size that is needed to represent the number, so it could be of size 1, to represent 1 for example. However, the size cannot be more than four bytes if an int is passed.
From Strings:
However, you will need to watch out, if the first byte is higher
0x7F
(as is in this case), where BigInteger would insert a 0x00 byte to the beginning of the array. This is needed to distinguish between positive and negative values.还可以换档——
Can also shift -
正确处理 ByteOrder 的简单解决方案:
ByteBuffer.allocate(4).order(ByteOrder.nativeOrder()).putInt(yourInt).array();
Simple solution which properly handles ByteOrder:
ByteBuffer.allocate(4).order(ByteOrder.nativeOrder()).putInt(yourInt).array();
这是一种应该能够正确完成工作的方法。
Here's a method that should do the job just right.
安卓非常简单
very easy with android
这会对你有所帮助。
This will help you.
这是我的解决方案:
还有
String
y 方法:It's my solution:
Also
String
y method: