Question

I have binary codes as 10111 , 100011, 11101111 etc. now what data structure should I use to store these codes so that minimum size is required to store them?

I can't use string array as size required will be more as compared than storing the decimal equivalent of above binary codes.

Was it helpful?

Solution

java.util.BitSet is designed for that if the length is not fixed.

OTHER TIPS

Depending on the length of the codes, simply use int or long.

If they'll be short, use byte, int, long (depending on how short).

If they'll be a bit longer, use an array of bytes, ints, or longs. For instance, if you need to store a 256-bit code, you can do that in a long[4].

If the length of the codes you need to store varies widely, you might consider either a class with a length member giving the number of bits and a byte, int, long, byte[], int[], or long[] member for storing them (depending on sizes and what kind of granularity you want). Or if you're really trying to pack as much in as you can, you can set aside some of the bits from your storage area to hold the number of bits in the code.

Each binary code could be split in portions by 8 bits (a byte). It would be necessary to define how to handle the tail if it is less than 8 bits. Byte arrays should work here nicely to store each portion.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top