[英]Get single bytes from multi-byte variable in java
How can I split a variable into single bytes in java? 如何在java中将变量拆分为单个字节? I have for example following snippet in C++: 我有例如C ++中的代码片段:
unsigned long someVar;
byte *p = (byte*)(void*) someVar; // byte being typedef unsigned char (from 0 to 255)
byte *bytes = new byte[sizeof(someVar)];
for(byte i = 0;i<sizeof(someVar);i++)
{
bytes[i] = *p++;
}
.... //do something with bytes
I want to accomplish the same under java, but I can't seem to find an obvious workaround. 我想在java下完成相同的工作,但我似乎找不到明显的解决方法。
There are two ways to do it with the ByteBuffer class. 使用ByteBuffer类有两种方法。 One is to create a new byte array dynamically. 一种是动态创建一个新的字节数组。
long value = 123;
byte[] bytes = ByteBuffer.allocate(8).putLong(value).array();
Another is to write to an existing array. 另一种是写入现有数组。
long value = 123;
byte[] bytes = new byte[8];
ByteBuffer.wrap(bytes).putLong(value);
// bytes now contains the byte representation of 123.
If you use Guava, there is a convenience Longs.toByteArray . 如果您使用Guava,则有一个方便的Longs.toByteArray 。 It is simply a wrapper for John's ByteBuffer answer above, but if you already use Guava, it's slightly "nicer" to read. 它只是上面John的ByteBuffer答案的一个包装器,但是如果你已经使用了Guava,那么阅读它会稍微“好”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.