Converting from string("01000001") to a byte and back.
AHHHHH! I give up. How do I convert a strings of ones and zeros into a byte that I can write to a binary file??? I've tried everything I can think of. Here is what i have so far:
Code:
string val = "01000001"; //Binary for letter 'A'
unsigned char a = 00000000;
//cout << a << endl;
unsigned char MASK = 1 << 0;
//cout << MASK << endl;
for (int i = val.size()-1; i >= 0; i--) {
a <<= 1;
if(val.substr(i,i+1)=="1"){
a |= MASK;
}
}
cout << a << endl;
fyi i want to write the file like this, so i need it in char arrays.
char * output; //load data, etc. etc.
writeFile(output, length, "output.txt");
Re: Converting from string("01000001") to a byte and back.
If you know precisely how many bits you're expecting to have, you can use a std::bitset to convert between string and unsigned long representations. This will only work if you have fewer than the number of bits in an unsigned long, of course.
Converting further to an unsigned char will require a static_cast. You could use a boost::numeric_cast if you wanted to check that you aren't losing data via the downcast.
Re: Converting from string("01000001") to a byte and back.
Thanks. Here is what I got for converting back and forth between strings and unsigned chars.
Code:
string myString1 = "01001010";
cout << myString1 << endl;
bitset<8> bitset1(myString1);
unsigned char a = static_cast<unsigned char>(bitset1.to_ulong());
cout << a << endl;
unsigned long l = static_cast<unsigned long>(a);
bitset<8> bitset2(l);
string myString2(bitset2.to_string<char,char_traits<char>,allocator<char> >());
cout << myString2 << endl;
Works great for me.
Btw, is there an easy interface to hold variable length bits and append them together? Or will I simply have to use strings?
Moreover, is there an easy way to write said bits to a file one a time? Or will I have to manually pad them into groups of 8? (Or is it 16?<--Not sure on this).
Re: Converting from string("01000001") to a byte and back.
You'll have to pad them into groups of 8 bits in order to write them to a file. No APIs I know of operate on a resolution lower than a byte.
Given that requirement, you could concatenate them as a string of chars (each being 8 bits) rather than a string of 1s and 0s (each being a character, and thus 64x less space-efficient).
Bookmarks