問題描述
我知道 Java 不允許無符號類型,所以我想知道它是如何將整數轉換為字節的.假設我有一個值為 255 的整數 a 并將整數轉換為一個字節.該值是否以字節 11111111 表示?換句話說,該值是更多地被視為一個有符號的 8 位整數,還是直接復制整數的最后 8 位?
I know Java doesn't allow unsigned types, so I was wondering how it casts an integer to a byte. Say I have an integer a with a value of 255 and I cast the integer to a byte. Is the value represented in the byte 11111111? In other words, is the value treated more as a signed 8 bit integer, or does it just directly copy the last 8 bits of the integer?
推薦答案
這叫做 縮小基元轉換.根據規范:
有符號整數到整數類型的窄化轉換T 只丟棄除n 個最低位之外的所有位,其中n 是用于表示類型 T 的位數.除了可能丟失有關數值大小的信息外,這還可能導致結果值的符號與輸入值的符號不同.
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.
所以這是您列出的第二個選項(直接復制最后 8 位).
So it's the second option you listed (directly copying the last 8 bits).
我不確定你是否知道有符號整數值是如何表示的,所以為了安全起見,我會指出字節值 1111 1111 在 二的補碼 系統(Java 使用).
I am unsure from your question whether or not you are aware of how signed integral values are represented, so just to be safe I'll point out that the byte value 1111 1111 is equal to -1 in the two's complement system (which Java uses).
這篇關于Java中的整數如何轉換為字節?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!