将原始字节值转换为Java类型

编程入门 行业动态 更新时间:2024-10-27 02:20:03
本文介绍了将原始字节值转换为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类型

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

发布评论

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

>www.elefans.com

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