在 Java 中將位元組轉換為無符號位元組

Haider Ali 2023年10月12日
在 Java 中將位元組轉換為無符號位元組

要了解如何在 Java 中將位元組轉換為無符號位元組的概念,你需要熟悉一些低階計算機概念。你需要了解所有關於轉換、位、位元組、字和諸如此類的資訊。讓我們深入瞭解一下。

在 Java 中將位元組轉換為無符號位元組

一個位元組有 8 位,計算有符號位元組和無符號位元組範圍的公式如下。

Signed Number min = -1 * 2 ^ (N - 1) = -1 * 2 ^ (7) = -128 max = 2 ^ (N - 1) - 1 = 2 ^ 7 - 1 = 127

    Unsigned Number min = 0 max = 2 ^ (N) -1 = 2 ^ (8) - 1 = 255

    // N is the number of bits

有符號數範圍較小的原因是保留了一位用於展示有符號符號;這就是範圍從 -128 到 127 的原因。Java 中沒有無符號位元組涉及無符號數。那麼,我們如何用 Java 製作它們呢?

你可以通過將它們轉換為新整數 (int) 並使用 0xff 遮蔽(按位與)該整數來生成無符號位元組。這樣,你將獲得最後 8 位,從而防止符號擴充套件。正如我們所知,0xFF = 1111 1111 在對原始位元組進行按位與運算後,將得到一個無符號位元組。

如果你還記得,當涉及到有符號位時,所有左邊的位都是 1。按位與運算會將它們變為 0,這就是我們對無符號數的表示。看看下面的程式碼。

import javax.swing.GroupLayout.Alignment;
// library to perform this task
public class Main {
  public static void main(String[] args) {
    byte byteData = -3; //-3 SIGNED  253 UNSIGNED Byte
    int Data = byteData & 0xff;
    System.out.println(Data);
  }
}

輸出:

253

這是一個非常簡單的過程,但它的概念有點複雜。瞭解更多關於 Java 中無符號位元組的資訊這裡

作者: Haider Ali
Haider Ali avatar Haider Ali avatar

Haider specializes in technical writing. He has a solid background in computer science that allows him to create engaging, original, and compelling technical tutorials. In his free time, he enjoys adding new skills to his repertoire and watching Netflix.

LinkedIn