Monday, June 15, 2026

C# How is data stored in byte array

Byte Array of different size can store different types of data. We will consider about integer data in this post. We will see how an interger data is stored as binary data.

System.Int32 represents an integer number (number without decimal point, not floating number) which takes exactly 32 bits to store the number in binary representation. Suppose that you declare a variable named population as follows:

int population =12345;

Here, int is alias of System.Int32.

Now, an integer number given in decimal digit representation can be converted into binary representation (or hexadecimal representation also).

The decimal number 12345 in binary representation is 11000000111001.

12345 🠊 11000000111001

How decimal number can be repesented in binary representation is explained below:

Rule: Divide by 2 repeatedly and collect remainders until Quotient is 0:

Division Quotient Remainder
12345 ÷ 2 6172 1
6172 ÷ 2 3086 0
3086 ÷ 2 1543 0
1543 ÷ 2 771 1
771 ÷ 2 385 1
385 ÷ 2 192 1
192 ÷ 2 96 0
96 ÷ 2 48 0
48 ÷ 2 24 0
24 ÷ 2 12 0
12 ÷ 2 6 0
6 ÷ 2 3 0
3 ÷ 2 1 1
1 ÷ 2 0 1

Read remainders from bottom to top and write 11000000111001₂ as binary representation:

Now,coming back to the topics of storing number in byte array. 

Declaring a byte array of size 4 is sufficient to store System.Int32 type data. (1 byte = 8 bits, So, 4 bytes = 32 bits)

byte[] arr = new byte[4];
int population =12345;

The number 12345 in binary representation is 11000000111001. So it will be 00000000 00000000 00110000 00111001 in byte array of size 4. Each byte will store 8 bits. 

But computers store multi-byte values using endianness. Most systems running C# today are little-endian, meaning the least significant byte comes first. So, actual storage will be in the reverse order for each byte: 00111001 00110000 00000000 00000000

So: Numeric / logical bit representation:

00000000 00000000 00110000 00111001

Actual byte array returned by BitConverter (little-endian):

byte[] bytes = BitConverter.GetBytes(12345); 
// 00111001 00110000 00000000 00000000

 

No comments:

Post a Comment

Hot Topics