Sandbox‎ > ‎IPT 2010-11‎ > ‎Josh's Sandbox‎ > ‎

Zone11: Binary Number System

posted Mar 12, 2010, 9:35 PM by Unknown user   [ updated Mar 15, 2010, 12:37 AM ]

Introduction

This post is on the Binary Number System. I will post this in parts, as it is a highly interesting topic from my perspective. Also something to do when I get bored.

Welcome to the endless tunnel that is ... binary. Binary is the simplest form of maths there is; 1s and 0s only. It is used in computer systems as there is little (or no) ambiguity with electrical signals/pulses and the transmitting and receiving of data.

Decimal and Binary

  • Our usual numbers are in base 10 (called Decimal); for any digit, once we add 1 to 9 our current digit becomes 0 and our new digit starts at 1
  • Binary is in base 2, meaning each digit is a 1 or a 0
  • A Binary digIT is called a bit for short
  • A byte is a series of 8 bits, an 8 digit binary number.

Converting from Decimal->Binary

  • To convert a binary number into decimal, you start with the digit on the right-hand side
  • If it is a 0, move on to the next digit on the left
  • If it is a 1, add 20 to the total
  • Perform this for the next digit on the left, except add 21 if necessary
  • Repeat for all digits


e.g. Convert a byte to decimal
01100001 = 0*27 + 1*26 + 1*25 + 0*24 + 0*23 + 0*22 + 0*21 + 1*20
               = 64 + 32 + 1
               = 97

python code for binary -> decimal
bin = raw_input("Enter the binary to convert.\n")
dec = 0
newbin = bin[::-1] #newbin = reversed bin
for i in xrange(len(newbin)):
dec += int(newbin[i])*(2**i)
print bin,"base 2 ==",dec,"base 10

Converting from Decimal->Binary

  • Converting from decimal to binary is very simple
  • E.g. converting a number N to binary
  • We start with N, and find out the remainder when divided by 2, this will either be a 1 or a 0 (N mod 2; represented as N%2)
    • If N is even, N%2 = 0
    • If N is odd, N%2 = 1
  • This remainder is our rightmost digit of our binary
  • We then repeat this process with N = N/2 until N = 0
  • Note if N is odd, we perform floor division (rounding down)
e.g. convert 97 to binary:
  • N = 97, so N%2 = 1
  • floor(N/2) = 48, N%2 = 0
  • N/2 = 24, N%2 = 0
  • N/2 = 12, N%2 = 0
  • N/2 = 6, N%2 = 0
  • N/2 = 3, N%2 = 1
  • floor(N/2) = 1, N%2 = 1
  • floor(N/2) = 0, so we stop
We then concatenate and reverse the results we got for N%2 at each step, (there are log2 N steps); giving us:
97 -> (0)1100001 (we can append the 0 at the front to make it one byte)





dsfsdfsdf

A binary tunnel

Comments