如何计算任何原始类型的值,当其值超出范围时。

huangapple go评论131阅读模式
英文:

How to calculate the value of any primitive , who has out of range value

问题

示例

byte x;
x = (byte)2355;
System.out.println(x);

那么,我如何计算 x 中的值?

<details>
<summary>英文:</summary>

Example

byte x;
x=(byte)2355;
System.out.println(x);

so, how can I calculate the value which will be in x;

</details>


# 答案1
**得分**: 2

```plaintext
`2355` 字面值被解释为一个 `int`,在Java中用以下32位表示:

    00000000000000000000100100110011

一个 `byte` 只有8位,所以你会失去前面的24位:

    00110011

转换回十进制,这将使你得到一个值为 `51`。

----------

你可以在[这里](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html)找到各种原始数据类型的位大小。在处理有符号原始数据类型时,也请记得考虑[二进制补码](https://en.wikipedia.org/wiki/Two%27s_complement)。
英文:

The 2355 literal value is interpreted as an int, which in Java is represented by the following 32 bits:

00000000000000000000100100110011

A byte has only 8 bits, so you lose the leading 24 bits:

00110011

Converted back to decimal, this leaves you with a value of 51.


You can find the bit sizes of the various primitive data types here. Also keep in mind that you need to take two's complement into account when dealing with signed primitives.

答案2

得分: 0

byte 数据类型的取值范围是从 -128 到 127(包括在内)。因此,如果您希望处理范围之外的数字,您可以尝试将数据类型转换为 shortintlong

英文:

The range of the byte data type is -128 to 127 (inclusive). So if you want to deal with numbers outside that range then you can try casting the data type to short, int or long.

huangapple
  • 本文由 发表于 2020年8月31日 17:23:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/63668140.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定