Compact packing algorithm.

Status
Not open for further replies.

Metasyntactic

Ars Legatus Legionis
31,808
Hey all, looking for some smarts on the following problem:

I have the following two function definitions:

Code:
struct S {
  int a;
  int b;
  bool c;
  bool d;
  int e;
  int f;
  bool g;
  bool h;
}

public static int[] encode(S value) {
  ... encode the value into an int[] ...
}

public static S decode(int[] encoded) {
  // decode the int[].  Note: only the values and the length
  // of the array are available here.
  ...
}

The intent is to be able to *losslessly* encode/decode any instance of that struct to/from an array of ints.

This problem can be solved trivially. For example:

Code:
public static int[] encode(S s) {
  return new [] { s.a, s.b, s.c ? 1 : 0, s.d ? 1 : 0, s.e, s.f, s.g ? 1 : 0, s.h ? 1 : 0 };
}

public static S decode(int[] en) {
  return new S { a = en[0], b = en[1], c = en[2] == 1, d = en[3] == 1,
                 e = en[4], f = en[5], g = en[6] == 1, h = en[7] == 1 };
}

However, that's hugely wasteful. 256 bits to store 132 bits of data. We can trivially see how we could improve things just by packing the bool parameters into one int instead of using 4 individual ints. i.e.

Code:
public static int[] encode(S s) {
  return new [] { s.a, s.b, s.e, s.f,
    (s.c ? 1 : 0) | (s.d ? (1 << 1 : 0) | (s.g ? (1 << 2) : 0) | (s.h ? (1 << 3) : 0) };
}

public static S decode(int[] en) {
  return new S { a = en[0], b = en[1], e = en[4], f = en[5], 
                 // unpack the bits into: c, d, g and h 
               };
}

So that's better. Only 160 bits instead of 256. However, 160 bits is still hugely wasteful. In practice, while those int inputs could potentially have any value, it's far more likely that they will fall into certain ranges.

For example, here are some things that we know about the input data.

S.a: Can cover the entire range of ints. But lower values are far more likely than higher values. 99% of the time it can fit in 20 bits.

S.b: Similar to A, except 99% of the time, it can fit in 10bits. If it is 0, then S.c and S.d will be 0.

S.c: more often 0 than 1.
S.d: more often 0 than 1.

S.e: 99% of the time it will fit in 4 bits.

S.f: Similar to A, except 99% of the time, it can fit in 10bits. If it is 0, then S.g and S.h will be 0.

S.g: more often 0 than 1.
S.h: more often 0 than 1.

Knowing that in the worst case we'll only need 5 ints (as shown above), one approach would be to can manually come up with a scheme that, based on the input values picks an encoding format that will be anywhere from 1-5 ints.

Decoding would then check the length of the array and properly unpack things accordingly. For example, we could imagine a 1-int encoding like so:

Code:
public static int[] encode(S value) {
  if (S.a < (1 << 16) && S.b < (1 << 5) && S.e < (1 << 5) && s.f < (1 << 5) &&
      !S.c && !S.d && !S.g && !S.h) {
    return new [] { (S.a << 16) | (S.b << 10) | (S.e << 5) | s.f }
  }
  ... rest of the cases.
}

public static S decode(int[] en) {
  if (en.length == 1) {
    // decode accordingly.  
  }
  ... rest of the cases
}

This would work but would:

a) require a lot of manual effort defining those encoded bit patterns.
2) be fragile in the presence of wanting to add more data to S.

So what i'm looking for is a generalized algorithm for taking these ints and booleans**, and producing packed arrays given the knowledge that the ints are normally low, and the booleans are normally false. At worst, the packing should never be more than Ceiling(input_bits / 32). i.e. worse case we can always just encode each int, and then pack all the booleans together. However, at best, you'd be able to fit these values far more often into 1-2 ints, and only rarely have to go beyond that.

It should be generalized in the sense that adding more inputs into S should only require tweaking things a tiny amount (as opposed to the above approaches i mentioned where you'd need to fix up a lot of encoding/decoding cases).

** We could also generalize this to just take in ints and not have booleans. After all, you could always just pack all booleans. The booleans are just interesting because they're more often 0 than 1.

Anyone have experience here, or thoughts on a good way to approach this?

Thanks!
 

jonhare

Seniorius Lurkius
1
Encoding integers into compact codes is done all the time in inverted indexes in search engines. Take a look at these schemes that give compact binary representations for small numbers:


  • * Unary coding: http://en.wikipedia.org/wiki/Unary_coding
    * Elias Delta coding: http://en.wikipedia.org/wiki/Elias_delta_coding
    * Elias Gamma coding: http://en.wikipedia.org/wiki/Elias_gamma_coding
    * Varint coding: https://developers.google.com/protocol-buffers/docs/encoding

For the booleans, obviously the simplest way is packed binary form, but there are some more compact alternatives. Assuming that all the booleans are stored together in the packed data structure, you could consider run-length coding (i.e. store that the first i values are 0, followed by j 1s, followed by k 0s, etc). If doing this you would use one of the above coding schemes to represent the run-length in as few bits as possible.
Another option is a variable-length code where you only store all the packed binary values up to the last 1; if you have all 0s, then you would store nothing, and the worst-case would be when only the last boolean is true you would have to store the entire bit string for all the booleans. Of course, you could even combine this with run-length coding if you have enough booleans to to make it worth-while (i.e. if the run-length can be coded with fewer bits than the number of false values).
 

Metasyntactic

Ars Legatus Legionis
31,808
[url=http:/civis/viewtopic.php?p=25610311#p25610311:3kqkqpjr said:
jonhare[/url]":3kqkqpjr]Encoding integers into compact codes is done all the time in inverted indexes in search engines. Take a look at these schemes that give compact binary representations for small numbers:


  • * Unary coding: http://en.wikipedia.org/wiki/Unary_coding
    * Elias Delta coding: http://en.wikipedia.org/wiki/Elias_delta_coding
    * Elias Gamma coding: http://en.wikipedia.org/wiki/Elias_gamma_coding
    * Varint coding: https://developers.google.com/protocol-buffers/docs/encoding
Unary coding would be pretty terrible for this use case. Any natural number N would need N bits to encode. (or did you mean just using it for a prefix?)

Varint coding is also not very suitable. Values need a minimum of a single byte to encode. For this use case (where there are 4 ints and several booleans) you'd need more than a single int to encode (even for the common cases where the values were quite small).

I will look into the two elias coding algorithms. They're new to me. Thanks!
 
I'm not sure if you're really serious about storing this as an array of ints, or whether you really meant to say that you want to encode it in the smallest number of bits per record. I'll assume the latter.

And I'm also going out and making the assumption that you're not just interested in storing one of these in the smallest possible space, but rather a big list of them.

If these are assumptions are wrong, then the following advice is irrelevant. Otherwise, read on.

Store the columns of your records serially, instead of the rows of the records.

This will enable you to use a different compression algorithm for each field in the record.

E.g. your bools might compress beautifully with run-length encoding, and your ints might do better with different Elias encodings.

Based on the problem description you might very well find that each int column has an empirically best encoding which differs from each other int column.

This is exactly the insight that's transforming the relational database industry right now. Edit: at about 10:00 minutes Stonebraker suggests that a common compression gain from column storage is 3-4.
 
Also, I'm working on an idea of my own for efficiently encoding sets of integers, which combines run-length encoding and column storage: namely, encoding chunks of integers by run-length encoding each binary digit in the chunk. Call it "column run length" encoding. It takes advantage of the fact that one need only store the actual value of the first bit in the column, and then parity runs.

E.g.:

0001
0011
0101
0001
0011
0001

Can be encoded like this:

(6,0)
(2,0),1,3
(1,0),1,2,1
(6,1)

I don't know if this has been published under a different name. One nice advantage of it is that it, too, like other column storage, enables different compression algorithms for different columns. E.g., you can compress the MSB's differently from the LSB's. I bring it up because it could be good for your use cases. If 99% of the time you can fit a 32-bit integer into 4 bits, that means you have huge runs of 0's in the MSB's.
 
[url=http:/civis/viewtopic.php?p=25611379#p25611379:qdo0ocsw said:
masonk[/url]":qdo0ocsw]I'm not sure if you're really serious about storing this as an array of ints,
It won't be precisely an array of ints. But it will be a known length and that number of ints. So, effectively an array (without the overhead of the actual array object itself).
or whether you really meant to say that you want to encode it in the smallest number of bits per record. I'll assume the latter.
Actually this isn't true. Assume the former. And this is actually quite important.

For example, if you have an algorithm that most of the time sits within the range 33-35 bits, that's going to be *worse* than someone else who can fit it in 32 bits 50% of the time and 64% 50% of the time. At the end of the day, you will be fit into the number of ints necessary to store your amount of bits.
And I'm also going out and making the assumption that you're not just interested in storing one of these in the smallest possible space, but rather a big list of them.
Yeah, there will be millions of these S's. However, we care about each encoding of S being compact. The encodings will not be concat'ed together. i.e. if you can fit one S into 33 bits, and one S into 20 bits. That will still be three ints (2 for the first S, and one for the second), not 2 ints.

Thanks!
 
Even if you do contrive some clever encoding that can fit your data into 32 bits, aren't you still going to have to decode it in order to operate on it programmatically? So why does it matter what form the data takes while encoded?

Also, have you done the math to find out what the theoretical entropy per struct is? It might be more than 32 bits, in which case you'll have proven that no encoding exists with the properties you're looking for.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
I think you're looking for a general purpose solution is at odds with your desire for maximal efficiently.

The PAQ stuff is basically PPM-eque with multiple models tubed to different inputs (and some very fancy stuff to pick which model is doing better, in this case so long as the distribution is not multi modal you should be okay with a distinct singular model, at which point you're just a special cased PPM).
Give us a few thousand examples and we can start getting creative...
 
[url=http:/civis/viewtopic.php?p=25613745#p25613745:29qk08ue said:
masonk[/url]":29qk08ue]Even if you do contrive some clever encoding that can fit your data into 32 bits, aren't you still going to have to decode it in order to operate on it programmatically?
Yes... :)
So why does it matter what form the data takes while encoded?
So that it doesn't take up a lot of memory while i'm not operating on. Take the simple examples above. Why store something as 256 bits when 160 would do?

I think i see the confusion though. If i was constantly needing to keep all those values uncompressed in memory, this would sort of be pointless.

But think of it more of a case where things will 99% of the time be in stored form and only a few S's will be uncompressed at a time. Does that help clarify things?

Thanks!
Also, have you done the math to find out what the theoretical entropy per struct is? It might be more than 32 bits, in which case you'll have proven that no encoding exists with the properties you're looking for.
I can trivially generate encodings that fit many of the S values into 32 bits. A simple example is:

use 20 bits for A, and 10 bits for E. This fits the common case where B and F are zero (and thus c, d, g, and h are zero as well).

However, to do this, i need ot write the custom checks on encoding/decoding.

The goal of this discussion was to learn if there was algorithsm out there that would do this generally based on some knowledge of value probabilities and relations between fields. Thanks!
 
So that it doesn't take up a lot of memory while i'm not operating on. Take the simple examples above. Why store something as 256 bits when 160 would do?

I think my suggestion works for you. Have you thought about it? It actually solves your problem. You can decode just the next N structs for any value of N and keep the rest encoded. Each field can use an off-the-shelf stream compression algorithm, or each field can use an off-the-shelf file compression algorithm and you simply encode and decode in manageable chunks, the size of which you have complete control over.

Edit for a tangent: a zero value doesn't mean zero entropy. You get information when you learn that a random variable's value is zero. But Ion the other hand I realized that I was wrong and having a theoretical entropy > 32 doesn't mean that no values can be less than 32 bits in a variable length encoding. So, my bad.
 
[url=http:/civis/viewtopic.php?p=25614713#p25614713:15tb0v7b said:
masonk[/url]":15tb0v7b]
So that it doesn't take up a lot of memory while i'm not operating on. Take the simple examples above. Why store something as 256 bits when 160 would do?

I think my suggestion works for you.
Sorry, can you be more specific? Which one are you referring to?

Thanks!
 
[url=http:/civis/viewtopic.php?p=25613771#p25613771:3iof52sp said:
ShuggyCoUk[/url]":3iof52sp]I think you're looking for a general purpose solution is at odds with your desire for maximal efficiently.
That's very very very possible. Off the bat i know i can write a customized solution. I was just hoping i was treading ground were smarter people had solved the generalized case. if not, c'est la vie. It just means a little more work on my end. Thanks! :)
 
Code:
ID ----a---  -b- -c- --d---- ---e--- --f---- -g- -h-
1         0   0   0    123      12      0     0   0
2       123   0   0    0         9      1     1   1
3     12130   1   1    9302     16     12     1   0
4         0   0   0    123      12      0     0   0
5

Don't try to encode the rows of your data. Encode the columns of your data.

Now you can select an encoding mechanism that fits each column. The bools get run length encoding. The usually-4-bit column gets varint encoding. Etc.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
Compressing in blocks (possibly using column compression) will almost certainly win in terms of memory usage in a general form. This is of course assuming you can afford the cost of the chunk access and decompression cost.

Sticking with a 1:1 scheme you can think about what your hand rolled solution would be:

You create a "structural representation tree" where every leaf node represents some decomposition of the struct where fields are either implicit, or have a guaranteed smaller form and is encodable in Sn bits. Further each leaf node has a probability associated with it Pn of that form occurring.
Each branch in the tree may have some degrees of freedom to it (including not branching at all) and this is how you can tune the number of distinct leaf nodes.
Then you have an optimisation problem to balance the cost of the bit representation to represent the leaf node type plus the sum of Sn * Pn for all n

There are some constraints, assuming you are working in words of some length not bits, but they can be applied when constructing the possible trees.

For your problem description I suspect this is brute force-able, in general it might need the usual suspects of optimisation heuristics to get a decent solution.

Some tweaks involve Huffman encoding or similar for the node type identifiers, or indeed specific sub parts of the encoded form are possible. The latter makes your size calculations a tad more complex though.

Edit: de-ipadified[1] my writing a touch
1. It's a word, honest guv.
 

w00key

Ars Legatus Legionis
10,099
Subscriptor
Practical version: just pack it as int[], int[], bool[], bool[], int[], int[], bool[], bool[], where bool[] are encoded at one bit per element. Then compress the stream to get rid of the entropy waste. Depending on your encoding/decoding speed requirements, you can stick to deflate for balance or go crazy with lzo/lzo2/lzma/ppmd.

There's no way you can beat this without spending huge amounts of time.


Source: we encode 100M-1G .txt logs into ~3% of the original size pretty much this way after parsing the structure. Inflating these files takes < 200ms.
 

Richard Berg

Ars Legatus Legionis
43,037
Subscriptor
[url=http:/civis/viewtopic.php?p=25614787#p25614787:2wfakvd1 said:
Metasyntactic[/url]":2wfakvd1]
[url=http:/civis/viewtopic.php?p=25613771#p25613771:2wfakvd1 said:
ShuggyCoUk[/url]":2wfakvd1]I think you're looking for a general purpose solution is at odds with your desire for maximal efficiently.
That's very very very possible. Off the bat i know i can write a customized solution. I was just hoping i was treading ground were smarter people had solved the generalized case. if not, c'est la vie. It just means a little more work on my end. Thanks! :)
Thing is, your specifics are very specific this time. Every time I try to envision what it means to generalize your final "encode" fn (32 packed bits that covers the various 99% cases), I end up with code generation or moral equivalent... sounds hard to write & verify (that is, even harder than maintaining an admittedly brittle collection of hand-rolled algos)... and on the theoretical front it feels like cheating.

Mind you, I think simpler ideas (columnar storage, Gamma coding, chunking, discriminated unions) are likely to be good enough.
 

topham

Ars Legatus Legionis
13,756
Subscriptor
Use the high bit of each byte to indicate each field, 1 bits for include next byte, 0 bit for end of field. It wastes a few upper bits, but you've indicated your general case is lower numbers anyway; the worst case scenario is an extra byte per field. Bit fields in structure should be merged, but you can treat them the same as ints if you add more in the future (8 bit fields would require 2 bytes, but 7 would only require 1.

Values 0 - 254 are stored in a single byte. Values 255 - 16384 require 2, 16389 - 2097152 requires 3 etc.
 

Jonathon

Ars Legatus Legionis
17,645
Subscriptor
[url=http:/civis/viewtopic.php?p=25615903#p25615903:1yfw09dq said:
topham[/url]":1yfw09dq]Use the high bit of each byte to indicate each field, 1 bits for include next byte, 0 bit for end of field. It wastes a few upper bits, but you've indicated your general case is lower numbers anyway; the worst case scenario is an extra byte per field. Bit fields in structure should be merged, but you can treat them the same as ints if you add more in the future (8 bit fields would require 2 bytes, but 7 would only require 1.

Values 0 - 254 are stored in a single byte. Values 255 - 16384 require 2, 16389 - 2097152 requires 3 etc.
That's how protobuf's varint encoding works. ;)
 
[url=http:/civis/viewtopic.php?p=25614815#p25614815:3nq49pw7 said:
LordFrith[/url]":3nq49pw7]With all the requirements and specifications, would a union be better? Basically, have a bit selector pick out which structure you wanted.
That seems to be good restatement of the original problem in far less words than i spent :)

The problem is trying to form the specific structures without manually defining them.
 
Thing is, your specifics are very specific this time.
Agreed. However, going into the question, i wasn't sure if that was a deal breaker for most algorithms out there, or if much smarter people than me had figured it out :)

If it turns out the generic versions are simply too much overhead over the hand rolled stuff, then i'll just go the latter round.
Every time I try to envision what it means to generalize your final "encode" fn (32 packed bits that covers the various 99% cases), I end up with code generation or moral equivalent... sounds hard to write & verify (that is, even harder than maintaining an admittedly brittle collection of hand-rolled algos)... and on the theoretical front it feels like cheating.

Mind you, I think simpler ideas (columnar storage, Gamma coding, chunking, discriminated unions) are likely to be good enough.
I'm going to try doing some of the gamma/delta encoding systems when i get a chance. I'll see how they compare against maybe handling the 1-2 int versions myself, and hten falling back to 5ints if those don't suffice. Good data will help me determine how i should proceed.

Unfortunately, the columnar storage approach simply doesn't apply in this case. The values are not processed in bulk, and the system must process things independently.

i.e. the functions, as i defined them at the beginning, are the API you must conform to. You can't do: "encode(S[] values)" instead of "encode(S value)". Sorry! :(
 
[url=http:/civis/viewtopic.php?p=25616037#p25616037:28jyqq3c said:
Jonathon[/url]":28jyqq3c]
[url=http:/civis/viewtopic.php?p=25615903#p25615903:28jyqq3c said:
topham[/url]":28jyqq3c]Use the high bit of each byte to indicate each field, 1 bits for include next byte, 0 bit for end of field. It wastes a few upper bits, but you've indicated your general case is lower numbers anyway; the worst case scenario is an extra byte per field. Bit fields in structure should be merged, but you can treat them the same as ints if you add more in the future (8 bit fields would require 2 bytes, but 7 would only require 1.

Values 0 - 254 are stored in a single byte. Values 255 - 16384 require 2, 16389 - 2097152 requires 3 etc.
That's how protobuf's varint encoding works. ;)
Yup. And it's also hugely wasteful here unfortunately. Maybe a simpler form using nibble based varints instead of byte based ones.
 
For your problem description I suspect this is brute force-able, in general it might need the usual suspects of optimisation heuristics to get a decent solution.
Agreed. I think this is a very reasonable approach to go down. The results should be near as good as manually writing it myself with the benefit of having it machine generated to avoid simple math errors. It can also be easily modified in the future to add more items to S.

Thanks!
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
I would postulate that shrinking their memory representation when in a cache might enable significant improvements in the size of the active cache, and how much of it fits in level 1/2/3 cache.

If the lookup of them becomes the bottleneck for whatever algorithms are running then spending massive amounts of effort to reduce the memory footprint of them wins, especially when you consider how fast modern CPUS even in the mobile space) compared to their memory sub systems. you can do an awful lot of maths/bit twiddling to save a main memory access, and mindbogglingly large amounts to reduce faults that hit permanent storage.

Just a guess though, I confess to being most intrigued by whatever Meta is doing :)

TIL: mindbogglingly is one word according to my spellchecker.
 

S. Carton

Ars Scholae Palatinae
937
A simple and effective way to tackle this might use a variant of the varint scheme and a spec definition.

If we make the varint's stride tunable, we can adjust it for optimality when we have representative data samples.

So our spec defines our struct, K defines the varint bit stride (4 for extra arbitrariness!):

Code:
K = 4

def varint_encode(bit_len, n):
	while 1:
		for i in range(bit_len):
			yield n & 1
			n = n >> 1
		if n > 0:
			yield 1
		else:
			yield 0
			break

def varint_decode(bit_len, it):
	num = []
	while 1:
		for i in range(bit_len):
			num.append(it.next())
		if it.next() == 0:
			res = 0
			for i, k in enumerate(num):
				res += (2 ** i) * k
			return res
		
def bit_encode(n):
	(yield 1) if n == 1 else (yield 0)

def bit_decode(it):
	return it.next()
	
def int_encode(n):
	bit_len = K
	for res in varint_encode(bit_len, n): yield res
		
def int_decode(it):
	bit_len = K
	n = varint_decode(bit_len, it)
	return n
	
specs = ['int', 'int', 'bool', 'bool', 'int', 'int', 'bool', 'bool'] 
encoder = {'int': int_encode, 'bool': bit_encode}
decoder = {'int': int_decode, 'bool': bit_decode}
	
def encode(specs, l):
	for spec, n in zip(specs, l):
		for res in encoder[spec](n): yield res
	
def decode(specs, it):
	res = []
	for spec in specs:
		n = decoder[spec](it)
		res.append(n)
	return res
	
def size(l):
	return len(list(encode(specs, l)))
	
def test_sizes():
	ls = [	[0,0,1,0,0,0,0,1],
			[5,5,1,0,6,6,0,1],
			[50,50,1,0,60,60,0,1],
			[5000,5000,1,0,600,600,0,1],
			[50000,50000,1,0,6000,60000,0,1],
			[50000000,50000000,1,0,6000000,60000000,0,1]]
	for l in ls:
		if decode(specs, encode(specs, l)) != l:
			raise borked_coding
		print l, 'bit size', size(l)
		print

The bit sizes we get look nice for small numbers:

Code:
>>> test_sizes()
[0, 0, 1, 0, 0, 0, 0, 1] bit size 24
[5, 5, 1, 0, 6, 6, 0, 1] bit size 24
[50, 50, 1, 0, 60, 60, 0, 1] bit size 44
[5000, 5000, 1, 0, 600, 600, 0, 1] bit size 74
[50000, 50000, 1, 0, 6000, 60000, 0, 1] bit size 84
[50000000, 50000000, 1, 0, 6000000, 60000000, 0, 1] bit size 139
>>>

This does not fit the maximum size requirement, though it can be easily modified to do so by packing a varint - fixed length switch into the bits left over from packing the booleans into an int, and choosing either varint or 32-bit representation based on the data.

It can also be modified to store per-int strides if different int fields are expected to have wildly different sizes (by eg encoding the stride in unary followed by the varint) or other stuff; the nice thing is it is simple to implement and modify.

Edit: oh, and I assumed ints >= 0, but that's trivially changeable.
 

topham

Ars Legatus Legionis
13,756
Subscriptor
[url=http:/civis/viewtopic.php?p=25616037#p25616037:2vdm2g8h said:
Jonathon[/url]":2vdm2g8h]
[url=http:/civis/viewtopic.php?p=25615903#p25615903:2vdm2g8h said:
topham[/url]":2vdm2g8h]Use the high bit of each byte to indicate each field, 1 bits for include next byte, 0 bit for end of field. It wastes a few upper bits, but you've indicated your general case is lower numbers anyway; the worst case scenario is an extra byte per field. Bit fields in structure should be merged, but you can treat them the same as ints if you add more in the future (8 bit fields would require 2 bytes, but 7 would only require 1.

Values 0 - 254 are stored in a single byte. Values 255 - 16384 require 2, 16389 - 2097152 requires 3 etc.
That's how protobuf's varint encoding works. ;)

Which I didn't read the spec of until after I posted.
 

Hattori HANZo

Ars Scholae Palatinae
1,205
Hmm. I am pretty sure you thought of this already or it is a prototypic example of one of the encodings mentioned. Or it falls in the category of "too complex to handle" or "not extendable enough".

Byte[0]: The four bools, then four bools indicating a short or a long format for the 4 ints.
E.g. if the fifth bit is set high, S.a will be encoded in 20 bit. If the sixth bit is set, S.b will be encoded in 10 bit, etc...
So in the best case and assuming 32 bit ints, you get 8+20+10+4+10=52 bits < 2 ints. In the worst case you get 5 ints, which is at least not worse. In between you get at most 2 ints plus one for each long format. If you have 3 or more long formatted numbers, it will be 1 int plus the number of long formatted ones. Calculating their offsets is also possible.

Given that we have a few bits to spare to fill 2 ints in the best case, we might use two bits per int to store to indicate the format. 00 is 4 bit, 01 is 10 bit, 10 is 20 bit and 11 is full length. Depending on how the 1% case looks, being able to encode the usually 10 bits in 20 bits might help further.


We would still only use 56 bits of the 64 we would have in our best case. Depending on extensible this should be and how much pain it is allowed to cause, we might add a 4 bit or 8 bit number as the first element, indicating the number of encoded variables. In this case generality suffers for bools.
So we could do it like this:
4b (number of bools)
the bools
4b (number of ints)
the bit field specifying their encoding
the compacted ints

Yes, this is basically making an int stream out of the byte array and putting your own datatypes in it.
 
Status
Not open for further replies.