Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put bit sequence into bytes (C/C++)

I have a couple of integers, for example (in binary represetation):

00001000, 01111111, 10000000, 00000001

and I need to put them in sequence to array of bytes(chars), without the leading zeros, like so:

10001111 11110000 0001000

I understand that it is must be done by bit shifting with <<,>> and using binary or |. But I can't find the correct algorithm, can you suggest the best approach?

The integers I need to put there are unsigned long long ints, so the length of one can be anywhere from 1 bit to 8 bytes (64 bits).

like image 203
Smaug Avatar asked Mar 10 '12 15:03

Smaug


1 Answers

You could use a std::bitset:

#include <bitset>
#include <iostream>

int main() {
    unsigned i = 242122534;
    std::bitset<sizeof(i) * 8> bits;
    bits = i;
    std::cout << bits.to_string() << "\n";
}
like image 52
strcat Avatar answered Sep 29 '22 06:09

strcat