CCS C Software and Maintenance Offers
FAQFAQ   FAQForum Help   FAQOfficial CCS Support   SearchSearch  RegisterRegister 

ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

CCS does not monitor this forum on a regular basis.

Please do not post bug reports on this forum. Send them to support@ccsinfo.com

Displaying binary numbers

 
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion
View previous topic :: View next topic  
Author Message
Guest








Displaying binary numbers
PostPosted: Thu Feb 19, 2009 1:17 pm     Reply with quote

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

View user's profile Send private message Visit poster's website

PostPosted: Thu Feb 19, 2009 1:38 pm     Reply with quote

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

View user's profile Send private message

PostPosted: Thu Feb 19, 2009 1:45 pm     Reply with quote

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

View user's profile Send private message

PostPosted: Thu Feb 19, 2009 3:40 pm     Reply with quote

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.
Display posts from previous:   
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion All times are GMT - 6 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group