c++ - Store a non numeric string as binary integer -


this question has answer here:

how convert string

string = "hello";  

to it's bit representation stored in int

int b = 0110100001100101011011000110110001101111 

here a , b being equivalent.

you cannot store long character sequence (e.g. std::string) inside int (or inside long int) because size of character 8-bit , length of int 32-bit, therefore 32-bit long int can store 4 characters.

if limit length of number of characters, can store them following example shows:

#include <iostream> #include <string> #include <climits>  int main() {     std::string foo = "hello";     unsigned long bar = 0ul;      for(std::size_t = 0; < foo.size() && < sizeof(bar); ++i)         bar |= static_cast<unsigned long>(foo[i]) << (char_bit * i);      std::cout << "test: " << std::hex << bar << std::endl; } 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -