简体   繁体   中英

How to convert char to an array of bits in c++?

I need to get each Character of a string as a sequence of bits either in an array or just traverse over it in a loop, either way works. This is something I used to do in ASM way back, and am not sure how that can be done in c++.

EDIT: I am trying to replicate what I did sometime back with asm, reading a file in memory and traversing it bit by bit, manipulate each bit, do some more cyphering and save it back.

Basically a simple Encryption. Its not a homework neither it is a project.

The Standard Library has a class for that, std::bitset . It may be what you need.

You can iterate through it using bit operators:

unsigned char c = 'a'
for(int i = 0; i < 8; i++)
{
  std::cout << (c >> i) & 1 << std::endl;
}

This will shift c to the right for i position, and use bitwise AND to get value of the least significant bit.

You'll want to look using a bit-mask and bit-wise operators & , | , >> and/or maybe << . I'm guessing that you'll want to store them in an array of bool type, something like bool bitArray[256];

Of course it is standard practice to just use unsigned char for storing a bunch of bits.

You can just loop over the character and check the bits with a bitmask

char c;
for (int i = 0; i < 8; ++i) {
    bool is_set = c & (1 << i);
    std::out << "Bit " << i << ": " << is_set << '\n';
}

or a string

std::string s;
for (auto p = s.begin(); p != s.end(); ++p) {
    char c = *p;
    // loop over the bits
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM