View previous topic :: View next topic |
Author |
Message |
Guest
|
Displaying binary numbers |
Posted: Thu Feb 19, 2009 1:17 pm |
|
|
I want to work in binary for some aspects of my programming but I can't find anything on binary for C. Such as in a PRINTF statement I want to display a variable as a binary number. From what I have found you can only display as a decimal, hex or octal numbers. Anyone have any ideas??
Thanks |
|
 |
treitmey
Joined: 23 Jan 2004 Posts: 1094 Location: Appleton,WI USA
|
|
Posted: Thu Feb 19, 2009 1:38 pm |
|
|
Code: | //=== display_binary ===//
void display_binary(char c){
int8 i=7;
putc('0');
putc('b');
do
{
if( c & 0x80 ) putc('1');
else putc('0');
c <<= 1;
} while(i--);
} |
|
|
 |
aaaaamartin
Joined: 17 Apr 2005 Posts: 39 Location: Germany Stuttgart
|
|
Posted: Thu Feb 19, 2009 1:45 pm |
|
|
This is done using the binary operators & | ^ .
Basically you need to check each bit of your variable.
You can also use bitwise shifting << >> in a loop to test all bits one by one.
Here's an example, for keeping it simple a non-recursive approach.
Code: |
int x;
int foo = 170;
// Testing the lefmost 8 Bits and print them.
for(x=7; x>=0; x--) {
if( foo & (1 << x) > 0) {
putc('1');
} else {
putc('0');
}
}
|
|
|
 |
ckielstra
Joined: 18 Mar 2004 Posts: 3680 Location: The Netherlands
|
|
Posted: Thu Feb 19, 2009 3:40 pm |
|
|
Code: | for(x=7; x>=0; x--) { | Be careful, in CCS the integers are unsigned by default. After 0 the value of x wraps to 255 which is >= 0 and the loop will never end.
Change to: Code: | for(x=8; x>0; x--) { | Or change x to be a signed integer. |
|
 |
|