logo
Course thumb

The C programming language made simple

Reversing all the bits in an integer

#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char* argv[]) { int a = 13; printf("%d\n", a); long long i; for (i = 0; i < sizeof(int); i++) { printf("%02hhx ", ((unsigned char*)&a)[i]); } int reversed = 0; for (i = 0; i < 32; i++) { reversed |= ((a >> i) & 1) << (32 - i - 1); } printf("\n%d\n", reversed); for (i = 0; i < sizeof(int); i++) { printf("%02hhx ", ((unsigned char*)&a)[i]); } return 0; }