Mohith's blog

Day 01 - Bits & Bytes

Bits & Bytes

Gottfried Wilhelm Leibniz formalized binary arithmetic in 1703 so that Mohith Chandra Konduru can share his thoughts on bits & bytes.

The first time i came across binary was prolly when i am doing my 12th it didn't pique me because i hated electronics and circuits. But in my first semester i was asked to write a c language code which converts decimal number to octal number which i failed miserably because i had no clue about octal number ( PS : i prepared for decimal to binary conversion tho)


Byte

Byte is 8 layers of bits.

1 Byte=8 Bits28=256

THE INTEGER : 4 Bytes

A good mental model is to stop thinking about "32 bits" and instead think about 32 tiny light switches. Each switch doubles the value of the one to its right.

Each byte has a different "place value," just like decimal numbers:

Decimal:

4  7  2  5
│  │  │  └── 5 × 10^0
│  │  └───── 2 × 10^1
│  └──────── 7 × 10^2
└─────────── 4 × 10^3

A 32-bit binary number works the same way, except the base is 256 instead of 10:

Byte1  Byte2  Byte3  Byte4

Byte1 × 256^3
+ Byte2 × 256^2
+ Byte3 × 256^1
+ Byte4 × 256^0

Endianness ( THE NEW THING FOR ME )

The terms "big-endian" and "little-endian", however, were coined by:

Danny Cohen

He introduced them in his famous 1980 paper:

"On Holy Wars and a Plea for Peace"

The names come from Gulliver's Travels by Jonathan Swift.

In the story, two groups argue over which end of a boiled egg should be cracked first:

Danny Cohen used this as a humorous analogy for programmers arguing over whether the most significant byte or the least significant byte should come first in memory.

(PS : this guy is my spirit animal ngl)

Big-Endian (The Human Way)

Stores the Most Significant Byte first.

Address 100: 11
Address 101: 22
Address 102: 33
Address 103: 44

This is how humans read (left to right). If you print the memory out, it looks exactly like the number. Internet protocols (TCP/IP) use Big-Endian.

Little-Endian (The Computer Way)

Stores the Least Significant Byte first.

Address 100: 44
Address 101: 33
Address 102: 22
Address 103: 11

This looks backwards to us, but it's very efficient for computer processors when doing math. Almost all modern processors (Intel, AMD, Apple Silicon) use Little-Endian internally.


DATAVIEW ( ANOTHER NEW THING )

A computer doesn't know what data means.

It only sees bytes.

That's just 4 bytes.

Nothing more.

Whether those bytes are:

depends entirely on how you interpret them.

This interpretation is the data view.


DataView + Endianness

This is where DataView becomes really useful.

Suppose memory contains:

12 34 56 78

Reading as Big Endian

0x12345678

Reading as Little Endian

0x78563412

Same bytes.

Different interpretation.

JavaScript even lets you choose:

view.getUint32(0, false); // Big-endian
view.getUint32(0, true);  // Little-endian