Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert char to it's ascii binary code

Tags:

c++

c

binary

All I want is to go from 'a' to 0110 0001

like image 290
David Hurrolds Avatar asked Apr 22 '11 07:04

David Hurrolds


3 Answers

if you write int i = 'a'; you get you want since all numbers physically are base 2. But if it's needed to get a string with ones and zeros then here is an example

/* itoa example */
#include <stdio.h>
#include <stdlib.h>

int main ()
{
  int i = 'a';
  char buffer [33]; //the variable you will store i's new value (binary value) in
  _itoa_s(i,buffer,2);
  printf ("binary: %s\n",buffer);
  return 0;
}
like image 190
Andrey Sboev Avatar answered Oct 20 '22 06:10

Andrey Sboev


I may write an own one: Just be careful!

enum
{
  O32_LITTLE_ENDIAN = 0x03020100ul,
  O32_BIG_ENDIAN = 0x00010203ul,
  O32_PDP_ENDIAN = 0x01000302ul
};

static const union { unsigned char bytes[4]; uint32_t value; } o32_host_order =
  { { 0, 1, 2, 3 } };

#define O32_HOST_ORDER (o32_host_order.value)


template <class T> ostream & operator << ( ostream &os, const T &value )
{
  size_t i = sizeof(T);
  const char * val = "01";
  const unsigned char * addr = reinterpret_cast<const unsigned char *>(&value);
// x86
#if ( O32_HOST_ORDER == O32_LITTLE_ENDIAN )
  while ( i > 0 )
  {
    --i;
    os << val[bool(addr[i] & 128)];
    os << val[bool(addr[i] & 64)];
    os << val[bool(addr[i] & 32)];
    os << val[bool(addr[i] & 16)];
    os << val[bool(addr[i] & 8)];
    os << val[bool(addr[i] & 4)];
    os << val[bool(addr[i] & 2)];
    os << val[bool(addr[i] & 1)];
  }
// PowerPC
#else
  size_t j = 0;
  while ( j < i )
  {
    os << val[bool(addr[j] & 128)];
    os << val[bool(addr[j] & 64)];
    os << val[bool(addr[j] & 32)];
    os << val[bool(addr[j] & 16)];
    os << val[bool(addr[j] & 8)];
    os << val[bool(addr[j] & 4)];
    os << val[bool(addr[j] & 2)];
    os << val[bool(addr[j] & 1)];
    ++j;
  }
#endif
  return os;
}

Big endian testing: link.

like image 39
Naszta Avatar answered Oct 20 '22 06:10

Naszta


#include <cmath>
#include <iostream>
#include <string>
#include <cstring>
#include <cctype>
#include <cstdlib>

using namespace std;

char*  toBinary(char* doubleDigit)
{
  int digit = atoi(doubleDigit);
  char* binary = new char();

  int x = 0 ;
  for(int i = 9 ; digit != 0; i--)
  {
    //cout << "i"<< i<<endl;
    if(digit-pow(2,i)>=0)
    {
      digit = digit- pow(2,i);
      binary[x]= '2';
      binary[x+1]='^';
      binary[x+2]=i+'0';
      binary[x+3]= '+';
    x+=4;

    }

  }
  return binary;
}

int main()
{
 char value[3]={'8','2','0'};



 cout<< toBinary(value); 



  return 0 ;
}`enter code here`
like image 38
Jacques Avatar answered Oct 20 '22 04:10

Jacques