Skip to content

Instantly share code, notes, and snippets.

@mikeymop
Last active March 29, 2024 23:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikeymop/2d866adb119b51946364b98922263349 to your computer and use it in GitHub Desktop.
Save mikeymop/2d866adb119b51946364b98922263349 to your computer and use it in GitHub Desktop.
Swap Endian-ness C
#include<stdio.h>
#include<assert.h>
/**
Accumulate into res |
1) Shift 8*i bits right, fill left in with 0xFF
( val >> (i * 8)
2) Shifts the isolated val left 8*i bits into res.
<< (size - i) * 8
3) Uses bitwise OR operation to accumulate the flipped bytes into res.
res = res | ...
eg:
0x6971a69e >> 0xFFFFFF69 .... 0x69000000
0x6971a69e >> 0xFFFFFF71 .... 0x69710000
0x6971a69e >> 0xFFFFFFa6 .... 0x6971a600
0x6971a69e >> 0xFFFFFF9e .... 0x6971a69e
Working example:
mod: 9e
res: 9e000000
mod: a6
res: 9ea60000
mod: 71
res: 9ea67100
mod: 69
res: 9ea67169
**/
int flip_endian(int val) {
int res = 0;
int size = sizeof(int) - 1;
for (int i = 0; i <= size; i++) {
res = res | (( val >> (i * 8) & 0xFF) << (size - i) * 8);
}
return res;
}
int main() {
int value = 0x6971a69e;
int result = flip_endian(value);
printf("Input: 0x%x Result: 0x%x \n", value, result);
assert(result == 0x9ea67169);
return 0;
}
@mikeymop
Copy link
Author

gcc ./flip_bytes.c -o fb

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment