# Integer to Binary

Discussion in 'C Programming' started by Andrew, Sep 30, 2003.

1. ### AndrewGuest

Hi I don't know if this is a common question or not

I was wondering How I could convert an Integer to a byte in C is there a
function that does this and if not could someone explain the math to me to
be able to do this

Andrew, Sep 30, 2003

2. ### Ben PfaffGuest

"Andrew" <> writes:

> I was wondering How I could convert an Integer to a byte in C is there a
> function that does this and if not could someone explain the math to me to
> be able to do this

int integer = 123; /* A variable of an integer type. */
char byte = integer; /* Convert it to a byte. */
--
"Give me a couple of years and a large research grant,
and I'll give you a receipt." --Richard Heathfield

Ben Pfaff, Sep 30, 2003

3. ### Micah CowanGuest

"Andrew" <> writes:

> Hi I don't know if this is a common question or not
>
> I was wondering How I could convert an Integer to a byte in C is there a
> function that does this and if not could someone explain the math to me to
> be able to do this

I don't think the above is what you're actually asking. Judging
by the subject line, I'll hazard a guess that what you really
want is to convert an int variable into a string representation
of the binary value. I'll interpret your "to a byte" as a request
to represent this value to 8 places (bytes may have much more
than 8 binary places: I'm assuming you meant "octet").

Without giving you any code (our policy on this newsgroup is
generally not to write code, but to comment on it), I'd recommend
an algorithm such as: walk down from 7 to 0, checking the
corresponding bit in your variable using the left-bitwise-shift and
bitwise-and operators; output "1" if the bit is set, "0"
otherwise.

Note that the above will only work for values less than or equal
to two to the power of seven; but I'm assuming this was an input