Skip to content

Instantly share code, notes, and snippets.

@azat
Created November 26, 2023 20:54
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 azat/14a515fc561eca404d9242dee257256f to your computer and use it in GitHub Desktop.
Save azat/14a515fc561eca404d9242dee257256f to your computer and use it in GitHub Desktop.
#include <limits.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
const char * arg = argv[1];
uint64_t in_host = strtoll(arg, NULL, 16);
uint64_t in_network = __bswap_64(in_host);
uint64_t out_host = 0;
unsigned char * data;
data = (unsigned char *)&in_network;
for (ssize_t i = sizeof(uint64_t) * (CHAR_BIT - 1), pos = 0; i >= 0; i -= CHAR_BIT) {
/* out_host |= (uint64_t)(data[pos++] & 0xff) << i; */
/* out_host |= (uint64_t)((unsigned char)data[pos++]) << i; */
printf("data[i] = %x\n", data[pos]);
out_host |= (uint64_t)data[pos++] << i; // bug
printf("out_host = 0x%lx\n", out_host);
}
uint64_t out_network;
data = (unsigned char *)&out_network;
for (ssize_t i = sizeof(uint64_t) * (CHAR_BIT - 1), pos = 0; i >= 0; i -= CHAR_BIT) {
data[pos++] = out_host >> i & 0xFFu;
}
printf("arg=%s, in_host=0x%lx, in_network=0x%lx, out_host=0x%lx, out_network=0x%lx\n", arg, in_host, in_network, out_host, out_network);
return 0;
}
@azat
Copy link
Author

azat commented Nov 26, 2023

$ /tmp/le-test1 deadbeaf | grep 0xafbeadde00000000
arg=deadbeaf, in_host=0xdeadbeaf, in_network=0xafbeadde00000000, out_host=0xdeadbeaf, out_network=0xafbeadde00000000

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