Sunday, February 13, 2011

Binary Numbers



While programming Microcontrollers in C, most of the time we have to deal with registers. We may have to 'SET' the bits of a register, 'CLEAR' the bits of a register or 'CHECK' the status of a particular bit of a register. Before we do all this, let us first take a look at binary numbers and conversion to decimal number system.


A register is simply a collection of some bits.
When you pick up a microcontroller's datasheet, it'll say that, that particular microcontroller is a '8 bit Microcontroller' or '4 bit microcontroller' etc. It means that the register is 8 bits or 4 bits long respectively.
Now, each bit of this register can hold either a '0' (zero) or '1' (one).


Let's consider a variable 'A' which has a binary value 1101 (read as, one one zero one).
To convert A to decimal form, follow the following steps:

  • Assign precedence values 0,1,2,3..and so on, to each binary bit starting from the right most bit.
  • Thus in the case of A:






  •  Now, multiply each bit with 2^precedence value. Then add up all the results. 

 Therefore, A (in decimal form) = 1x23 + 1x22 + 0x21 + 1x20 = 1x8 + 1x4 + 0x2 + 1x1 = 8+4+0+1=13
Thus, decimal form of 1101 is 13.
Here, A was a 4 bit register.
Now, consider A to be an 8 bit register. The maximum binary value possible for A=11111111.
Assigning precedence values to A




 Using the same method again, we get A (in decimal form)= 255. Thus, the maximum value of an 8 bit register is 255.


Binary Numbers in C:


When you write A=101, in a C program, the compiler will interpret it as one hundred and one, which is a decimal number. To specify that a number is binary, we need to prefix a '0b' before that number.
The statement, 


A=0b11001101;


implies that A stores a binary value 11001101 (one one zero zero one one zero one). The bit pattern 11001101 is assigned to A. Here, A is assumed to be a 8 but register. If A were a 4 bit register, then only the first 4 bits, from the right would be stored and the rest would be neglected.


No comments:

Post a Comment