Last active
December 22, 2015 05:29
-
-
Save kevinlynx/6424506 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <assert.h> | |
typedef unsigned __int64 uint64; | |
typedef unsigned char byte; | |
void setBit(byte *data, int pos) { | |
byte bits[] = { | |
0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 | |
}; | |
/* note the position starts from 1, not 0 */ | |
data[pos / 8] |= bits[pos % 8 - 1]; | |
} | |
#define OFFSET_PTR(i, o) (((byte*)i) + o) | |
uint64 htoni64(uint64 i) { | |
uint64 r = 0; | |
*OFFSET_PTR(&r, 0) = *OFFSET_PTR(&i, 7); | |
*OFFSET_PTR(&r, 1) = *OFFSET_PTR(&i, 6); | |
*OFFSET_PTR(&r, 2) = *OFFSET_PTR(&i, 5); | |
*OFFSET_PTR(&r, 3) = *OFFSET_PTR(&i, 4); | |
*OFFSET_PTR(&r, 4) = *OFFSET_PTR(&i, 3); | |
*OFFSET_PTR(&r, 5) = *OFFSET_PTR(&i, 2); | |
*OFFSET_PTR(&r, 6) = *OFFSET_PTR(&i, 1); | |
*OFFSET_PTR(&r, 7) = *OFFSET_PTR(&i, 0); | |
return r; | |
} | |
/* | |
Because the bit position is defined in network byte order (big-endian), but the integer | |
represented on i386 is little-endian byte order. Or we can say the bit position is counted | |
from the start address. | |
*/ | |
int main(int, char **) { | |
uint64 a = 0x0020000000C00012; | |
uint64 b = 0; | |
setBit((byte*) &b, 11); | |
setBit((byte*) &b, 41); | |
setBit((byte*) &b, 42); | |
setBit((byte*) &b, 60); | |
setBit((byte*) &b, 63); | |
uint64 c = htoni64(b); | |
assert(a == c); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment