Skip to content

Instantly share code, notes, and snippets.

@coocood
Last active August 29, 2015 14:22
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 coocood/80219e4e2a6d71e39a55 to your computer and use it in GitHub Desktop.
Save coocood/80219e4e2a6d71e39a55 to your computer and use it in GitHub Desktop.
Double codec
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