java - Get byte representation of int, using only 3 bytes -


what's nice, readable way of getting byte representation (i.e. byte[]) of int, using 3 bytes (instead of 4)? i'm using hadoop/hbase , bytes utility class has tobytes function use 4 bytes.

ideally, i'd nice, readable way of encoding few bytes possible, i.e. if number fits in 1 byte use one.

please note i'm storing in byte[], know length of array , variable length encoding not necessary. finding elegant way cast.

a general solution impossible.

if possible, apply function iteratively obtain unlimited compression of data.

your domain might have constraints on integers allow them compressed 24-bits. if there such constraints, please explain them in question.

a common variable size encoding use 7 bits of each byte data, , high bit flag indicate when current byte last.


you can predict number of bytes needed encode int a utility method on integer:

int n = 4 - integer.numberofleadingzeros(x) / 8; byte[] enc = new byte[n]; while (n-- > 0) enc[n] = (byte) ((x >>> (n * 8)) & 0xff); 

note encode 0 empty array, , other values in little-endian format. these aspects modified few more operations.


Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

php - Get uncommon values from two or more arrays -

Adding duplicate array rows in Php -