Skip to content

Instantly share code, notes, and snippets.

@umgefahren
Last active March 6, 2022 15:24
Show Gist options
  • Save umgefahren/680efdf17b7d0618d44173add1c8bb65 to your computer and use it in GitHub Desktop.
Save umgefahren/680efdf17b7d0618d44173add1c8bb65 to your computer and use it in GitHub Desktop.
Bitfields in C
#include <stdio.h>
int main() {
unsigned int number = 1203;
short found_one = 0;
for (int i = (sizeof(unsigned int) * 8) - 1; i >= 0; i--) {
if (number & (1u << i)) {
putchar('1');
found_one = 1;
} else if (found_one) {
putchar('0');
}
}
printf("\n");
return 0;
}
#include <iostream>
int main() {
unsigned int number = 1203;
bool found = false;
for (int i = (sizeof(unsigned int) * 8) - 1; i >= 0; i--) {
if (number & (1u << i)) {
std::cout << "1";
found = true;
} else if (found) {
std::cout << "0";
}
}
std::cout << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment