理解Java无符号数 [英] Understanding Java unsigned numbers

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

问题描述

我想了解如何将已签名的号码转换为无符号号码。

I want to understand how to convert signed number into unsigned.

我可以说:

byte number = 127; // '1111111'

为了使它无符号我必须选择更大的数据类型' short'并应用值为0x00ff的AND运算符。

In order to make it unsigned I have to choose "bigger" data type 'short' and apply AND operator with value 0x00ff.

short number2;  
number2 = number & 0x00ff;

为什么这个号码是无符号的?

Why does it make the number unsigned?

推荐答案

Java实际上没有无符号原语。

Java doesn't actually have unsigned primitives.

值127实际上由'01111111'表示,第一位是符号(0为正)。

The value 127 is actually represented by '01111111' the first bit being the sign (0 is positive).

无符号字节可以保存0到255的值,但127是有符号字节的最大值。由于一个字节有8位,而有一个字节消耗一个来保持符号。
因此,如果要表示大于127的值,则需要使用具有更多位数的更大类型。较大的类型也有一个保留位用于符号,但它至少有8位用于实际值,因此你可以表示值255。

An unsigned byte would be able to hold values 0 to 255, but 127 is the maximum for a signed byte. Since a byte has 8 bits, and the signed one consumes one to hold the sign. So if you want to represent values larger than 127 you need to use a bigger type that has a greater number of bits. The greater type also has a reserved bit for sign, but it has at least 8 bits used for the actual values, so you can represent the value 255.

这就是说,你应该避免使用byte和short,因为它们存在问题。您会注意到我将结果转换为short,因为运算符实际上返回int。你应该坚持使用java中的int和long,因为它们实现得更好。

That being said, you should probably avoid using byte and short because there are issues with them. You'll notice i cast the result to short, since the operators actually return int. You should just stick to int and long in java since they are implemented better.

编辑:AND运算符使其无符号,因为符号位是short的第一位,并将保存字节值的8位复制到short的最后8位。因此,如果您有一个负数,则第一位为1(表示它为负)实际上成为该值的一部分。并且空头总是积极的,因为它的符号位是2的幂的两个高点受到卖空的影响。

the AND operator makes it unsigned since the sign bit is the first bit of the short, and you copy the 8 bits holding the value of the byte to the last 8 bits of the short. So if you have a negative number the first bit which is 1 (that means it's negative) actually becomes part of the value. And the short will always be positive since its sign bit is at two high of a power of two to be affected by the short.

 byte:             10101101
                    ||||||| <- actual value
short:     0000000010101101
            ||||||||||||||| <- actual value

编辑2:请注意,因为负值使用两个补码表示该值可能不是您所期望的。所有正值保持不变。

但-128 = 0x10000000将变为128

-127 = 0x10000001将变为129

等等直到-1 = 0x11111111,这将变为255

Edit 2: Take note though that since the negative values use two's complement representation the value might not be what you expect it. all the positive values remain the same.
But -128 = 0x10000000 will become 128
-127 = 0x10000001 will become 129
and so on until -1 = 0x11111111 which will become 255

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

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