Last active
March 6, 2022 15:24
-
-
Save umgefahren/680efdf17b7d0618d44173add1c8bb65 to your computer and use it in GitHub Desktop.
Bitfields in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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