将原始字节值转换为Java类型 [英] Converting raw-byte values into Java types

查看:122
本文介绍了将原始字节值转换为Java类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将原始字节值转换为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类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆