Byte variables & byte arrays
Series Overview
This article is part of the series. Below are links to all posts in the series:- Byte data type
- Python bytes vs bytearray
- Java byte range signed
A byte is a unit of memory composed of 8 bits. Each byte can store 256 different values (2^8). From 0 to 255, if unsigned.
Bytes are used to represent various data types, including:
- Characters
- Numbers
- Raw data (images, sounds, compressed files)
Let’s have a look at how we can store and represent them.
Python does not support creating a standalone byte as a variable. However, it does support byte arrays: bytes and bytearray.
The first is immutable, whereas the second is mutable.
Create an immutable object of length 3, initialized with empty bytes:
a: bytes = bytes(3)
print(b[0]) # output: 0
Create a mutable object of length 4:
b: bytearray = bytearray(4)
b[0] = 255
print(b[0]) # output: 255
You see, we are assigning 255 to the first byte. Number 255 (decimal) will be converted to a binary system: 11111111 (binary).
You see, it takes 8 bits. Here we go! By storing 255 in our byte variable, we can fill it out to the brim.
You can convert bytearray to bytes (and vice versa) if needed:
a = bytes(b)
print(a[0])
You see that they are unsigned, therefore capable of storing values from 0 to 255 (256 in total).
Java has standalone byte variable datatype support:
byte a1 = 127;
byte a2 = -127;
System.out.println(a1);
System.out.println(a2);
Java goes another way than Python. Java does support signs. A byte contains 8 bits; you have to reserve one bit for the sign (0 for positive, 1 for negative). Therefore, you are left with 7 bits.
Remember how to find a count of numbers that fits into X bits? Yeah, it is 2^x. In our case, 2^7 = 128. Since we have to store 0 as well, we have to subtract 1 from 128. Eventually, we end up with 127.
That is the explanation why -127 is the lowest possible value in Java’s byte variable and +127 is the highest.
byte arrays are also supported in Java:
byte[] arr = {a1, a2};
System.out.println(Arrays.toString(arr));