Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Programming - Convert an integer to binary

Tags:

c

binary

i was hopefully after some tips opposed to solutions as this is homework and i want to solve it myself

I am firstly very new to C. In fact i have never done any before, though i have previous java experience from modules at university.

I am trying to write a programme that converts a single integer in to binary. I am only allowed to use bitwise operations and no library functions

Can anyone possibly suggest some ideas about how i would go about doing this. Obviously i dont want code or anything, just some ideas as to what avenues to explore as currenty i am a little confused and have no plan of attack. Well, make that a lot confused :D

thanks very much

like image 346
leo Avatar asked Jan 23 '23 15:01

leo


2 Answers

Think about about what you can do with bitwise operators.

E.g. you can test whether a bit is 1 or 0 like this:

int bit = value & 1;

You can also shift the bits in an int like this:

val = val >> 1;

To test the i'th bit in an int you can do this:

int bit = (value >> i) & 1;

Hopefully that's enough hints to get you started.

like image 187
Paul R Avatar answered Jan 27 '23 01:01

Paul R


Tear it apart bit by bit. Use shifting. Handling more than one bit at a time can be done with a lookup table.

like image 36
Ignacio Vazquez-Abrams Avatar answered Jan 27 '23 02:01

Ignacio Vazquez-Abrams