0

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.

9
  • 1
    @user93353 nothing :) Don't have slightest of idea how to go about it. Commented Dec 11, 2012 at 16:03
  • What are you really trying to do? Commented Dec 11, 2012 at 16:11
  • std::bitset has a constructor that accepts std::string. Commented Dec 11, 2012 at 16:11
  • 1
    @user93353: Perhaps, but I doubt it, and even if it were homework, officially that's OK. You can choose not to answer homework questions, but people are not forbidden from asking them. In any case, it's irrelevant if this is homework. StudentX is posing an XY problem, where they are trying to accomplish X by doing Y and asking how to do Y, where the interesting question is "what is X?" Commented Dec 11, 2012 at 16:24
  • 1
    @user93353: I agree with your link, but it bears no relation to any reason why you would have replied with the comment, "Homework, possibly." Commented Dec 11, 2012 at 16:32

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

Comments

6

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

Comments

2

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.

Comments

2

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.