Saumesh
Saumesh

Reputation: 81

Bit data type in Java

I am writing a program, in Java, which need bit processing, and manipulations. But I could not find any "bit" level primitive datatype. Is there any way in Java to define "bit" datatype? In C/C++, we can tell compiler how many bits to allocate for variables storage as

struct bit {
    unsigned int value : 1;   // 1 bit to store value
};

How can I do same thing in Java?

Upvotes: 4

Views: 15119

Answers (2)

Jim Garrison
Jim Garrison

Reputation: 86774

Depends on what you mean by "bit".

If you want single bits use a boolean and true/false.

If you want multi-bit fields you'll have to use an integer type (byte, short, int or long) and do the masking yourself. There's also BitSet for an OO implementation, but it's likely to be slower than masking for small (<64 bits) sets, although better for readability.

Upvotes: 3

Elliott Frisch
Elliott Frisch

Reputation: 201497

boolean or Boolean with true or false (or Boolean.TRUE / Boolean.FALSE). Both of which can be used with autoboxing and unboxing. There is also a BitSet for handling a vector of bits.

Upvotes: 5

Related Questions