gpt4 book ai didi

java - 原始类型的转换

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:09:40 25 4
gpt4 key购买 nike

我是 Java 初学者。即使经过长时间的尝试,我也无法理解这一行。

字节数=(byte)135;

这一行给出结果 -121 为什么它是有符号数?

谁能详细说一下?

最佳答案

在 Java 中,byte 总是有符号的,并且它们在 -128127 的范围内。当 int 文字 135 向下转换为 byte 时,结果为负数,因为第 8 位已设置。

 1000 0111

具体来说,JLS, Section 5.1.3 , 状态:

A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the sign of the resulting value to differ from the sign of the input value.

当您将 int 字面值(例如 135)转换为 byte 时,这是一个窄化原始转换。

关于java - 原始类型的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26369301/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com