Skip to content

Instantly share code, notes, and snippets.

@bdss58
Created August 25, 2018 04:18
Show Gist options
  • Save bdss58/2a28f6da154374efc6fe240bd796ed21 to your computer and use it in GitHub Desktop.
Save bdss58/2a28f6da154374efc6fe240bd796ed21 to your computer and use it in GitHub Desktop.
print each byte of integer in binary format
#include <stdio.h>
void pbits(char);
int main() {
int n = 1025;
char* p = (char*)&n;
for (int i = 0; i < sizeof(n); i++) {
printf("%d byte: ", i);
pbits(*(p+i));
}
return 0;
}
void pbits(char p) {
int scaner = 1;
char bits[8];
for (int i = 0; i < 8; i++) {
if ((p & (scaner << i)) > 0) {
bits[7-i] = '1';
} else {
bits[7-i] = '0';
}
}
for (int i = 0; i < sizeof(bits); i++) {
printf("%c", bits[i]);
}
printf("\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment