Last active
August 29, 2015 14:22
-
-
Save coocood/80219e4e2a6d71e39a55 to your computer and use it in GitHub Desktop.
Double codec
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
typedef union { | |
double dv; | |
long long unsigned int lv; | |
} doubleLong; | |
void memrev64(void *p) { | |
unsigned char *x = p, t; | |
t = x[0]; | |
x[0] = x[7]; | |
x[7] = t; | |
t = x[1]; | |
x[1] = x[6]; | |
x[6] = t; | |
t = x[2]; | |
x[2] = x[5]; | |
x[5] = t; | |
t = x[3]; | |
x[3] = x[4]; | |
x[4] = t; | |
} | |
void encodeDouble(char *encoded, double val) { | |
doubleLong x; | |
x.dv = val; | |
if (val >= 0) { | |
x.lv |= 1L<<63; | |
} else { | |
x.lv = ~x.lv; | |
} | |
memrev64(&x); | |
memcpy(encoded, &x, 8); | |
} | |
double decodeDouble(char *encoded) { | |
doubleLong x; | |
memcpy(&x, encoded, 8); | |
memrev64(&x); | |
if (x.lv & 1L<<63) { | |
x.lv &= ~(1L<<63); | |
} else { | |
x.lv = ~x.lv; | |
} | |
return x.dv; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment