Skip to content

Instantly share code, notes, and snippets.

@HyperPlay
Created August 28, 2019 04:13
Show Gist options
  • Save HyperPlay/1f2549b7091c9e717cba28db60d8ec8d to your computer and use it in GitHub Desktop.
Save HyperPlay/1f2549b7091c9e717cba28db60d8ec8d to your computer and use it in GitHub Desktop.
Byte to bit conversion without bitset from the standard library.
#include <iostream>
using std::cout, std::endl, std::string;
string byte_to_bits(uint8_t byte);
char bool_to_char(bool b);
int main() {
for (int n = 0; n < 256; n++) {
cout << byte_to_bits((uint8_t) n) << endl;
}
return 0;
}
string byte_to_bits(uint8_t byte) {
string s;
for (int i = 0; i < 8; i++) {
s.push_back(bool_to_char((bool) ((byte << i) & 128)));
}
return s;
}
char bool_to_char(bool b) {
return b ? '1' : '0';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment