0

Here's my procedure:

static void undo_bitstring(std::string& str) { 
    for (unsigned i = 0; i < str.length(); i += charbits) { 
        int ascii_val = 0; 
        for (unsigned j = 0; j < charbits; j++) { 
            if (str[i+j] == '1') ascii_val += (int)exp2(charbits-j-1);
        }
        str[i/charbits] = (char)ascii_val;
    }
    str.erase(str.begin()+str.size()/charbits,str.end());
}

where, just so you know,

charbits 

was defined by

static const size_t charbits = 8 * sizeof(char);

What is supposed to happen is, for example,

std::string str = "01010111";
undo_bitsring(str);

should change str to

"W"

since

0x2^7 + 1x2^6 + 0x2^5 + 1x2^4 + 0x2^3 + 1x2^2 + 1x2^1 + 1x2^0 
= 64 + 16 + 4 + 2 + 1
= 87

and

(int)'W' = 87

And of course this procedure is supposed to work for any string of 0's and 1's with a length that is a multiple of charbits. For instance,

std::string str = "010101110101011101010111";
undo_bitsring(str);

should change str to

"WWW"

On the tests I've run, the output just looks like a bunch of boxes with question marks inside them, indicating some sort of error.

Any ideas?

Am I totally going about this wrong in the first place? This is part of some encryption/decryption algorithm I'm trying to make.

  • 2
    Read about `std::bitset`. – Pete Becker Aug 07 '13 at 17:43
  • 1
    It worked for me when I compiled it on gcc and ran it. Both the `"W"` and `"WWW"` examples worked. – SirGuy Aug 07 '13 at 17:46
  • Your code works as it should. Check that you're actually using the code that you posted. Note also that `8 * sizeof(char)` is redundant as per the C++ standard. `sizeof(char)` is required to be `1` by the standard. – DUman Aug 07 '13 at 17:51
  • Maybe this post is related: http://stackoverflow.com/questions/111928/is-there-a-printf-converter-to-print-in-binary-format –  Aug 07 '13 at 17:55

1 Answers1

1

Do you know about the >> and << operators. These operators, when applied to an int will shift the bit 1 position right or left. It would probably be more reliable than using (int)exp2(charbits-j-1);

sevensevens
  • 1,703
  • 16
  • 27
  • `exp2` is a standard function in `` since C++11 so I really doubt using `<<` is any more reliable and probably results in the exact same code being emitted by the compiler. – SirGuy Aug 07 '13 at 17:53