Search code examples
c++bitset

String Binary conversion


I'm currently writing a simple program to convert a string into base64 by manipulating its bit values.

If I use the bitset function to convert a string into its bit values, how can I manipulate or store those values?

For example, if I do this:

std::cout << bitset<8>(cstring[i]) << std::endl;

I'm able to print out all the binary values I want. But I want to be able to manipulate these values. Do I have to convert into a string before I can operate on it, or can I operate on the bits directly.

More specifically I'd like to group the bits into groups of size 6 and change the value of those groups into an int value. Any help is appreciated, thanks!


Solution

  • I would recommend that instead of using bitset, you just perform the conversion to base64 the old-fashioned way. Take the three input bytes, as unsigned chars, and use simple bitwise shifts with a table lookup to convert them to base64.

    It's not really complicated. If

    unsigned char a, b, c;
    

    Are your input bytes then, (doing this from memory):

    int b1= (a >> 2);
    
    int b2= ((unsigned char)((a & 0x03) << 4)) | (unsigned char)(b >> 4);
    
    int b3= ((unsigned char)((b & 0x0F) << 2)) | (unsigned char)(c >> 6);
    
    int b4= c & 0x3F;
    

    No need to use bitsets. You say you're writing a simple program? Well, can't get much simpler than this. Here are your four integers. In the final step, use an array lookup to convert the values into the base64 alphabet.

    And if I made a typo here -- you get the general idea. You can look up and figure out the actual bitshifts on paper and pencil, and implement them the same way.