Re: how to convert char to binary?

From: Chris \( Val \) (chrisval_at_bigpond.com.au)
Date: 10/09/04


Date: Sun, 10 Oct 2004 01:17:34 +1000


"John Harrison" <john_andronicus@hotmail.com> wrote in message
news:2sq5vsF1ofjl8U1@uni-berlin.de...
|
| "Joseph" <wutongjoe@hotmail.com> wrote in message
| news:Xns957E10F5CAFDCwutongjoe@203.109.252.31...
| > Hi all,
| >
| > I was wondering if there is any lib or function could do the following
| > things:
| >
| > input: a char
| > output: 8 digits binary presentation for that given char
| >
| > Example:
| >
| > -------------------------
| > input: k
| > Hex=6B <-ASCII table 'k'
| > Binary = 0110 1011
| >
| > output: 0110 1011
| > done
| > -------------------------
| > input: K
| > Hex=4B <-ASCII table 'k'
| > Binary = 0100 1011
| >
| > output: 0100 1011
| > done
| >
| > --------------------------
| >
| > (I am only dealing with the ASCII printable chars,no UNICODE,no non-
| > printables)
| >
| > Am I clear with the question?
| > I want to make it standard and system independent(no windows/linux system
| > calls).
| > The only solution I came up with is to have a pre-computed table.Is there
| > any easier way of doing this ?
|
| Simplest way is to use bit manipulation, but it isn't the only way.
|
| #include <iostream>
| #include <limits.h>
|
| void print_char_as_binary(char ch)
| {
| int i = CHAR_BIT;
| while (i > 0)
| {
| -- i;
| std::cout << (ch&(1 << i) ? '1' : '0');
| }
| }

Simplest ? :-)

// ...
# include <bitset>
int main()
 {
  std::cout << std::bitset<CHAR_BIT>( 'K' )
            << std::endl;

  return 0;
 }

Cheers.
Chris Val



Relevant Pages

  • libs and constants
    ... I want to build a ".lib" library where I will have some constants. ... The constants are not only int, char, but also struct constants. ... This can work with constants int or char*, ...
    (comp.lang.c)
  • Re: how to convert char to binary?
    ... > I was wondering if there is any lib or function could do the following ... 8 digits binary presentation for that given char ... > I want to make it standard and system independent(no windows/linux system ... Simplest way is to use bit manipulation, but it isn't the only way. ...
    (comp.lang.cpp)
  • how to convert char to binary?
    ... I was wondering if there is any lib or function could do the following ... 8 digits binary presentation for that given char ... I want to make it standard and system independent(no windows/linux system ...
    (comp.lang.cpp)
  • Re: how to convert char to binary?
    ... >|> I was wondering if there is any lib or function could do the ... > int main ... how can I do it vice versa? ... from binary to char? ...
    (comp.lang.cpp)
  • Re: [MFC REQUEST] Filename completion in sh(1)
    ... * This code is derived from software contributed to The NetBSD Foundation ... +static const char * ... +static int ... void ckfree; ...
    (freebsd-current)