Thursday, April 28, 2011

Really basic programming maths (part 1)

So I've been trying to mentally do hexadecimal addition. I've found that I'm not very good at it.

I'm going to slowly explain how I go about working stuff out, with the hope that it will stick in my head and get easier. (Binary is written with the most significant bit first, and all numbers are unsigned.)

First of all there is how to think about numbers in binary and hex.

Decimal numbers get split up into multiples of powers of ten.

For example 4181 can be broken down as:
  • 4 x 103
  • 1 x 102
  • 8 x 101
  • 1 x 100

Remembering that all numbers raised to 0 are 1.

This applies to both binary and hexadecimal too.

So 0xFEED breaks down to:
  • F(15) x 10(16)3
  • E(14) x 10(16)2
  • E(14) x 10(16)1
  • D(13) x 10(16)0

The numbers in parenthesis are the decimal representations of the hexadecimal numbers.

And 0b1101 breaks down to:
  • 1(1) x 10(2)3
  • 1(1) x 10(2)2
  • 0(0) x 10(2)1
  • 1(1) x 10(2)0

The numbers in parenthesis are the decimal representations of the binary numbers.

Next up is the easy way to transition from hex to binary and back.

Since an individual hex digit takes up to a maximum of four bits, all hex numbers can be represented as collections of four bit numbers.

So 0x4432 can be broken down into 0b0100, 0b0100, 0b0011, 0b0010

This can be reversed. Say you have the 32bit number 0b10011100110100110101101011110011.

If you break it down into four bit chunks you get:
  • 0b1001
  • 0b1100
  • 0b1101
  • 0b0011
  • 0b0101
  • 0b1010
  • 0b1111
  • 0b0011

Each chunk can be represented as a hex digit:
  • 0x9
  • 0xC
  • 0xD
  • 0x3
  • 0x5
  • 0xA
  • 0xF
  • 0x3

Which gives us the number 0x9CD35AF3.

The difficult part comes in getting that number as decimal.

To do it from hex, you need to add up all the powers of sixteen that there are:
  • 9 x 167
  • 12 x 166
  • 13 x 165
  • 3 x 164
  • 5 x 163
  • 10 x 162
  • 15 x 161
  • 3 x 160

Which turns out to be: 2631097075. Not easy to calculate in your head. To do it from binary would take even longer as you would need to add up all the powers of two from 31 to 0.

Thus endeth part one.

No comments: