Java中的无符号字节 [英] Unsigned Bytes in Java

查看:203
本文介绍了Java中的无符号字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java中的字节默认是签名的。我在其他帖子上看到,使用无符号字节的解决方法类似于: int num =(int)bite& 0xFF

Bytes in Java are signed by default. I see on other posts that a workaround to have unsigned bytes is something similar to that: int num = (int) bite & 0xFF

有人可以向我解释为什么会这样做并将有符号字节转换为无符号字节然后转换为相应的整数? ANDing 一个字节,11111111会产生相同的字节 - 对吗?

Could someone please explain to me why this works and converts a signed byte to an unsigned byte and then its respective integer? ANDing a byte with 11111111 results in the same byte - right?

推荐答案

类型转换的优先级高于& 运算符。因此,您首先要转换为int,然后进行AND运算以屏蔽所有设置的高位,包括java使用的两个补码表示法的符号位,只留下正值原始字节。例如:

A typecast has a higher precedence than the & operator. Therefore you're first casting to an int, then ANDing in order to mask out all the high-order bits that are set, including the "sign bit" of the two's complement notation which java uses, leaving you with just the positive value of the original byte. E.g.:

let byte x = 11111111 = -1
then (int) x = 11111111 11111111 11111111 11111111
and x & 0xFF = 00000000 00000000 00000000 11111111 = 255

并且您已经有效地从原始字节中删除了该符号。

and you've effectively removed the sign from the original byte.

这篇关于Java中的无符号字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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