Author Topic: code to convert string into binary  (Read 914 times)

thrushitha

  • Full Member
  • ***
  • Posts: 26
code to convert string into binary
« on: September 30, 2011, 04:41:49 am »
sir, i hav a suiation wherein i need to convert string into binary and access each bit  eg: string is "MASK"
Can you  give me peice of code in C language, that performs above operation.


thanx in advance

administrator

  • Administrator
  • Full Member
  • *****
  • Posts: 69
Re: code to convert string into binary
« Reply #1 on: October 04, 2011, 03:34:13 pm »
sir, i hav a suiation wherein i need to convert string into binary and access each bit  eg: string is "MASK"
Can you  give me peice of code in C language, that performs above operation.
thanx in advance

#include <string.h>
#include <iostream.0>

void GetBits(char ch, int arr[8])
{
   char bitpos = 0x01;
   for(int j = 7; j >= 0; j--)
   {
      arr[j] = (ch & bitpos) ? 1 : 0;
      bitpos <<= 1;
   }
}

int _tmain(int argc, _TCHAR* argv[])
{
   char buf[] = "MASK";
   int arr[8];

   for(int i = 0; i < strlen(buf); i++)
   {
      GetBits(buf, arr);
      std::cout << buf << " : ";
      for(int j = 0; j < 8; j++)
      {
         std::cout << arr[j];
         if( j == 3)
            std::cout << " ";
      }
      std::cout << "\n";
   }

    return 0;
}

The above code will print the following:

M : 0100 1101
A : 0100 0001
S : 0101 0011
K : 0100 1011

Press any key to continue . . .

 


Disclaimer: This web site is for educational and informational purposes only. Click here to read the Disclaimer.
Content copyright 2010-2014. Kathiresan. All rights reserved.
This page is using SMF version 2.0.1