0

I am having a some trouble interpreting bits as bytes. What I have now is a string of either 8, 16, 24, etc. bits and I want to convert them into hex bytes. For example:

Lets say I have the following strings:

10100101 00110000

And I want to interpret each 4 as hex bytes so I would have

1010 as A, 0101 as 5, 0011 as 3, and 0000 as 0

Then when I put them together, I should get

A5 30 which would correspond to ¥0 based on their individual hex value. I'm not entirely sure on how to do this unfortunately. Might anyone have an idea to do this? If so, that'd be great! Thanks!

user200081
  • 563
  • 2
  • 12
  • 24

2 Answers2

3

This problem was already solved for you, in the C++ Standard Library's <bitset> header:

const unsigned long value1 = std::bitset<8>(std::string("10100101")).to_ulong();
const unsigned long value2 = std::bitset<8>(std::string("00110000")).to_ulong();

std::cout << std::hex << value1 << " " << std::hex << value2 << '\n';
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • I want to do it in a way that doesn't require the standard library, would that be possible? – user200081 Dec 01 '12 at 19:06
  • 2
    @user200081: Of course, but only with far more complex code. I refuse to spend time on such a requirement, unless you're programming a tiny microcontroller? – Lightness Races in Orbit Dec 01 '12 at 19:07
  • 2
    @user200081: Yes, of course. How'd you think the standard library does it? It isn't magic. But why ignore the standard library? – In silico Dec 01 '12 at 19:49
1

You should convert each individual group of 4 bits to one character, eg. with a table:

 char Hex[16]={ '0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};

A generic way to calculate this (without libraries between any 2 BASES) is to:

Step 1)

  my_number = 0; // start to read digits.
  while((a = read_digit(BASE))>=0) { 
       // read_digit should return -1 for non digit
       my_number=my_number * BASE + a;
       // optionally: if (count++ == 4) break;  /* read only 4 bits or digits */
  }

Step 2)

  // convert my_number to another base (eg. hex or decimal or octal or Base64)
  // by repeated division by BASE and storing the modulus
  while (my_number) {
       int modulus = my_number % BASE;
       my_number/=BASE;
       PUSH(modulus);
  }

Step 2.5)

  // Pop the numbers in range (0..BASE-1) from stack 
  // to output them from left to right
  while (POP(my_number) >=0) {     // assumes that pop returns <0 when empty
      cout << myTable[my_number];  // this can be selected for any base
  }
Aki Suihkonen
  • 19,144
  • 1
  • 36
  • 57