Skip to content

Instantly share code, notes, and snippets.

@od0x0
Created September 15, 2010 21:03
Show Gist options
  • Save od0x0/581482 to your computer and use it in GitHub Desktop.
Save od0x0/581482 to your computer and use it in GitHub Desktop.
/*
Platform Independent Endian Converter
Copyright (c) 2010 Oliver Daids
3-clause BSD
Note: This was not designed for speed, nor cleanliness, it was just a quick experiment to see if I could get a platform independent endian converter.
*/
#include <stdint.h>
static uint64_t UInt64TwoToThe(uint64_t exponent){
uint64_t x=1;
for(uint64_t i=0;i<exponent;i++) x*=2;
return x;
}
uint64_t UInt64From8Bytes(uint8_t* bytes, int bigendian){
uint64_t integer=0;
for(int i=0;i<8;i++){
int byteID=i;
if(bigendian) byteID=8-i-1;
integer+=(uint64_t)bytes[byteID]*UInt64TwoToThe(8*i);
}
return integer;
}
void UInt64To8Bytes(uint64_t integer, uint8_t* bytes, int bigendian){
for(int i=0;i<8;i++) bytes[i]=0;
uint64_t quotient=integer;
for(int i=0;i<8;i++){
int byteID=i;
if(bigendian) byteID=8-i-1;
if(quotient==0) break;
bytes[byteID]=quotient%256;
quotient/=256;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment