Velocity Reviews > Integer to Binary

# Integer to Binary

Andrew
Guest
Posts: n/a

 09-30-2003
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

Ben Pfaff
Guest
Posts: n/a

 09-30-2003
"Andrew" <(E-Mail Removed)> 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

Micah Cowan
Guest
Posts: n/a

 10-01-2003
"Andrew" <(E-Mail Removed)> 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

Post your attempt, and we'll be happy to comment on it.