Reputation: 97
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.
Upvotes: 2
Views: 3287
Reputation: 325
java.util.BitSet
is designed for that if the length is not fixed.
Upvotes: 10
Reputation: 1074595
If they'll be short, use byte
, int
, long
(depending on how short).
If they'll be a bit longer, use an array of byte
s, int
s, or long
s. 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.
Upvotes: 3
Reputation: 5410
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.
Upvotes: 0