nitin
nitin

Reputation: 97

what data structure should I use to store binary codes in java?

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

Answers (4)

ptriller
ptriller

Reputation: 325

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

Upvotes: 10

T.J. Crowder
T.J. Crowder

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 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.

Upvotes: 3

01es
01es

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

Stephan
Stephan

Reputation: 4443

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

Upvotes: 7

Related Questions