Convert Bytes to Unsigned Bytes in Java

Haider Ali Dec 31, 2021
Convert Bytes to Unsigned Bytes in Java

To understand the concept of how to convert bytes to unsigned bytes in Java, you need to be familiar with some low-level computer concepts. You need to know all about the conversions, bits, bytes, words, and whatnot. Let’s dive right in.

Convert Bytes to Unsigned Bytes in Java

There are 8 bits in one byte, and the formulas to calculate the range of signed bytes and unsigned bytes are as follows.

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

The reason for the small range of signed numbers is that one bit is reserved for showcasing signed symbols; that’s why the range is from -128 to 127. There are no unsigned bytes in Java when it comes to unsigned numbers. So, how do we make them in Java?

You can make an unsigned byte by casting them into a new integer (int) and masking (bitwise AND) that integer with the 0xff. That way, you will get the last 8 bits, preventing sign extension. As we know, 0xFF = 1111 1111, after its bitwise AND operation with the original byte, will give you an unsigned byte.

If you remember, when it comes to signed bits, all the left bits are 1. The bitwise AND operation will turn them to 0, and that’s our representation of an unsigned number. Take a look at the following code.

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);
    }
}

Output:

253

It is a pretty simple procedure, but its concept is a bit complex. Learn more about unsigned bytes in Java here.

Author: 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

Related Article - Java Bytes