英文:
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(包括在内)。因此,如果您希望处理范围之外的数字,您可以尝试将数据类型转换为 short
、int
或 long
。
英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论