Java如何在java中解析uint8? [英] Java how to parse uint8 in java?

查看:1651
本文介绍了Java如何在java中解析uint8?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个来自UDP数据包的 uint8 (无符号8位整数)。 Java仅使用签名的基元。如何使用java正确解析此数据结构?

I have a uint8 (unsigned 8 bit integer) coming in from a UDP packet. Java only uses signed primitives. How do I parse this data structure correctly with java?

推荐答案

只需将其作为一个字节读取,然后转换为int。

Simply read it as as a byte and then convert to an int.

byte in = udppacket.getByte(0); // whatever goes here
int uint8 = in & 0xFF;

需要位掩码,否则将位8设置为1的值转换为负值INT。示例:

The bitmask is needed, because otherwise, values with bit 8 set to 1 will be converted to a negative int. Example:

This:                                   10000000
Will result in: 11111111111111111111111110000000

因此,当您向其应用位掩码0xFF时,前导1将被取消。供您参考: 0xFF == 0b11111111

So when you afterwards apply the bitmask 0xFF to it, the leading 1's are getting cancelled out. For your information: 0xFF == 0b11111111

这篇关于Java如何在java中解析uint8?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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