将原始字节值转换为Java类型时遇到问题.我正在通过数据报套接字接收字节作为字节数组.我确切地知道哪个字节意味着什么,但是我不知道如何正确地转换它们(我的意思是我知道偏移量,但是不知道我认为接收到的内容是否正确;).
I have a problem with converting raw-bytes values into java types. I am receiving bytes by a datagram socket as a bytes array. I know exactly which bytes means what, but I don't know how to convert them appropriately (I mean I know offsets, but don't know if what I think I received is correct ;)).
例如,我想将16位unsigned short转换为java int类型.我在网上找到了一些示例,一个是:
For example, I want to convert 16 bit unsigned short into java int type. I found some examples in the web, the one is:
public int getUShort(byte[] bytes, int offset) { int b0 = bytes[offset] & oxFF; int b1 = bytes[offset + 1] & oxFF; return (b1 << 8) + (b0 << 0);另一个是相同的,但最后一行是:
Another one is the same but the last line is:
return (b0 << 8) + b1;当然,它给出不同的结果.哪一个是正确的?你能给我一个有效的例子,但是要花很长的时间来做吗?
Of course it gives different results. Which one is correct? Can you please give me also a valid example how to do the same but for an unsigned long?
提前谢谢!
推荐答案您可以使用DataInputStream或ByteBuffer读取各种类型.对于大多数操作,您可以将带符号类型用作无符号值.我编写了一个简单的类来说明如何使用签名类型,就好像它们是未签名的未签名
You can use DataInputStream or ByteBuffer to read the various types. You can use signed types as unsigned values for most operations just the same. I have written a simple class to illustrate how you can use the signed types as if they were unsigned Unsigned
ByteBuffer b = ByteBuffer.wrap(bytes); short s = b.getShort(); long l = b.getLong();更多推荐
将原始字节值转换为Java类型
发布评论