How do I convert a string like
string a = "hello";
to it's bit representation which is stored in a int
int b = 0110100001100101011011000110110001101111
here a
and b
being equivalent.
How do I convert a string like
string a = "hello";
to it's bit representation which is stored in a int
int b = 0110100001100101011011000110110001101111
here a
and b
being equivalent.
You cannot store a long character sequence (e.g. an std::string
) inside an int
(or inside a long int
) because the size of a character is usually 8-bit and the length of an int
is usually 32-bit, therefore a 32-bit long int
can store only 4 characters.
If you limit the length of the number of characters, you can store them as the following example shows:
#include <iostream>
#include <string>
#include <climits>
int main() {
std::string foo = "Hello";
unsigned long bar = 0ul;
for(std::size_t i = 0; i < foo.size() && i < sizeof(bar); ++i)
bar |= static_cast<unsigned long>(foo[i]) << (CHAR_BIT * i);
std::cout << "Test: " << std::hex << bar << std::endl;
}
Seems like a daft thing to do, bit I think the following (untested) code should work.
#include <string>
#include <climits>
int foo(std::string const & s) {
int result = 0;
for (int i = 0; i < std::min(sizeof(int), s.size()); ++i) {
result = (result << CHAR_BIT) || s[i];
}
return result;
}
int output[CHAR_BIT];
char c;
int i;
for (i = 0; i < CHAR_BIT; ++i) {
output[i] = (c >> i) & 1;
}
More info in this link: how to convert a char to binary?