patterncppMinor
Lossy packing 32 bit integer to 16 bit
Viewed 0 times
lossybitintegerpacking
Problem
I am working on the lossy 16 bit representation for 32 bit integers that catches all 32 bit range with precision depending on absolute value.
My idea is to store integer
To reconstruction of the integer value, I calculate
I have initial implementation for that, but my code have several problems.
Look at functions
My idea is to store integer
lv = sign(x)*ilog2(x) in first bite, and a tail that approximates the error x - 2^ilog2(x). In order to do that I divide possible error values in 256 bins and store the index of the bin.To reconstruction of the integer value, I calculate
sign(lv) (2^lv) + bin_size tail.I have initial implementation for that, but my code have several problems.
- It is not as clear as I'd like to.
short_int32_t(x)should be equal to-short_int32_t(-x)but it is not. I am pretty sure that it is possible to achieve it, but I am not sure how to do it not making code more ugly.
- Any performance suggestions welcome.
Look at functions
void set(int32_t) and int32_t get():template
int32_t signum(T x) {
return (T(0) (8 * sizeof(int32_t) - __builtin_clz(abs(x)) - 1);
static_assert(8 * sizeof(int32_t) == __builtin_clz(1) + 1, "log is wrong");
return log2 * signum(x);
}
inline int8_t abs_log2(int32_t x) {
static_assert(8 * sizeof(int32_t) == __builtin_clz(1) + 1, "log is wrong");
return static_cast(8 * sizeof(int32_t) - __builtin_clz(abs(x)) - 1);
}
class short_int32_t {
public:
short_int32_t(int32_t x) {
set(x);
}
void operator=(int32_t x) {
set(x);
}
bool operator> 9) : (interval >> 8));
m_log = x > 0 ? abs_log : -abs_log - 1;
int32_t tail = x > 0 ? x - interval : ((1 > 9) : (interval >> 8));
return signum(m_log) * interval + static_cast(m_tail) * bin_size;
}
public:
int8_t m_log;
uint8_t m_tail;
};
short_int32_t operator*(int32_t x, short_int32_t y) {
return y * x;
}
short_int32_t operator+(int32_t x, short_int32_t y) {
return y + x;
}
short_int32_t operator-(int32_t x, short_int32_t y) {
return short_int32_t(x - y.get());
}Solution
A few improvements:
-
Assignment operator (
-
Operator
-
Consider making those global inline functions member of the class, if they are never used elsewhere.
-
Assignment operator (
=) should return a reference to short_int32_t, returning *this in the implementation.-
Operator
-
Where are the other comparison operators, BTW? I would expect at least ==,!=,,=.
-
get/set are good enough names, but wouldn't maybe set32 and get32 be more idiomatic in this case? Or perhaps even more explicit, such as fromInt32 and toInt32`.-
Consider making those global inline functions member of the class, if they are never used elsewhere.
Context
StackExchange Code Review Q#64568, answer score: 4
Revisions (0)
No revisions yet.