Byte representations
Series Overview
This article is part of the series. Below are links to all posts in the series:- Byte representation numeral systems
- Hexadecimal conversion python Java
- Binary prefix programming
- Byte array hex format display
You can have a bunch of bytes, that being a png picture or an mp3 song all together. Notice that you can still represent each byte as a number!
That is a really important thing to keep in mind.
Bytes are represented in a binary numeral system in a computer’s memory, but you can represent them however you want. Hexadecimal numeral system is increasingly helpful there. Since it has 16 digits,
0, 1, 2, ... 8, 9, A, B, C, D, E, F
numbers, being represented in the hexadecimal system, are really short compared to their binary (and even decimal) representations.
Consider the number 255 (decimal). It is 11111111 in binary, but FF in hexadecimal! You can see the difference in length.
Alright, we can treat every possible byte as a number. Let’s have a look at this bunch of bytes:
00 ff fe 4d 08 a4 3c
We have 7 bytes here. Being represented in binary, this byte array would look like this:
00000000 11111111 11111110 1001101 0001000 10100100 00111100
And in decimal:
0 255 254 77 8 164 60
This is how you can look at a byte of an array in hexadecimal format in Python:
b: bytearray = bytearray(4)
b[0] = 255
print(hex(b[0])) # output: 0xff
Python uses a 0x prefix to work in hexadecimal format. Notice that you can set your bytes in a hexadecimal way as well:
b: bytearray = bytearray(4)
b[0] = 0xab
print(hex(b[0])) # output: 0xab
print(b[0]) # output: 171
You can also use a binary format with 0b prefix:
b: bytearray = bytearray(4)
b[0] = 0b1010
print(hex(b[0])) # output: 0xa
print(bin(b[0])) # output: 1010
print(b[0]) # output: 10
Java has the same prefixes:
byte a1 = 0b101;
byte a2 = 0x0f;
System.out.println(Integer.toHexString(a1));
System.out.println(Integer.toBinaryString(a2));