#include <stdio.h>
#include <stdint.h>
#include <assert.h>
#include <limits.h>
// 4 bit xor
// 4 bit position
// 16 bit integer / pattern
uint32_t encode(uint64_t v) {
uint16_t pattern = 0;
for(size_t i = 0; i < 4; ++i) {
uint16_t segment = v >> (i * 16);
if(segment != 0 &&
segment != 0xFFFF &&
segment != pattern &&
segment != (pattern ^ 0xFFFF)) {
assert(pattern == 0 && "Unable to encode number");
pattern = segment;
}
}
uint32_t result = pattern;
for(size_t i = 0; i < 4; ++i) {
uint16_t segment = v >> (i * 16);
if(segment == 0) {
} else if(segment == 0xFFFF) {
result |= 0x100000 << i;
} else if(segment == pattern) {
result |= 0x010000 << i;
} else if(segment == (pattern ^ 0xFFFF)) {
result |= (0x010000 << i) | (0x100000 << i);
} else {
assert(0 && "This should never happen");
}
}
return result;
}
uint64_t decode(uint32_t v) {
uint64_t result = 0;
for(size_t i = 0; i < 4; ++i) {
uint16_t segment = ((0x010000 << i) & v) ? (uint16_t)v : 0;
segment ^= ((0x100000 << i) & v) ? 0xFFFF : 0;
result |= (uint64_t)segment << (i * 16);
}
return result;
}
int main(void) {
uint64_t v = 0x60019FFEFFFF0000;
//uint64_t v = INT_MIN;
printf("%lx\n", v);
//return 0;
//uint64_t v = -255;
uint32_t e = encode(v);
uint64_t d = decode(e);
printf("%lx\n", d);
assert(v == d);
printf("encoded: %x\n", e);
return 0;
}