Reputation: 3890
Why ByteBuffer class doesn't provide method to read write boolean data type, is there any workaround?
Upvotes: 2
Views: 6242
Reputation: 19
The DataOutputStream
has a writeBoolean(boolean v)
method.
Internally, it does write(v ? 1 : 0)
. Using this convention, your code would look like
boolean v = <true|false>....
byteBuffer.put(v ? (byte)1 : (byte)0);
Upvotes: 0
Reputation: 533790
There is no standard on how a boolean should be written. There is any number of workarounds such as writing 0 or 1, 0 or -1, n
or y
, f
or T
, or the strings "false" or "true", or whatever you like. Or as others have suggested you might want to write only one bit instead of using one or more bytes.
Upvotes: 3
Reputation: 311023
Because on the wire there is no such thing as a boolean data type. There are just bytes, which can be treated as (a) booleans, (b) sequences of ASCII, (c) taken 2 at a time as shorts, (d) taken 4 at a time as ints, (e) taken 8 at a time as longs, ...
Upvotes: 2
Reputation: 234845
It's because boolean (1 bit) is the only plain-old data data type that's smaller than a Byte (8 bits).
So you are motivated to pack booleans for efficiency. But the techniques for that are best left to the user.
Upvotes: 2
Reputation: 73568
Boolean
is a 1-bit datatype. ByteBuffer
works with bytes. You'll have to decide yourself how you'll represent a boolean as a byte (such as 0 for false and 1 for true, or 0 for false and non-zero for true).
Upvotes: 6