0

while creating a contract between server and client apps should we use bits to represent bool values to optimise payload.

So far I have always come across bools in APIs. why dont we use bit to represent this info.

ZhaoGang
  • 4,491
  • 1
  • 27
  • 39
  • 1
    Because a Java boolean is the only single bit primitive there is. There is no other "bit" type (that's a primitive). – Elliott Frisch Jan 08 '19 at 03:50
  • Also, because optimizing below the level of `boolean` is rarely warranted ... if you do a full cost / benefit analysis, comparing the extra software complexity against the *actual* performance benefit of saving a few bits. – Stephen C Jan 08 '19 at 03:55
  • What do you perceive to be the difference between a "bool" and a "bit" that would cause the one to be preferred over the other? – Kevin Anderson Jan 08 '19 at 04:11
  • @ElliottFrisch `boolean` should not be a `bit` sized data type. https://stackoverflow.com/questions/383551/what-is-the-size-of-a-boolean-variable-in-java – ZhaoGang Jan 08 '19 at 05:13
  • @ZhaoGang Precisely how many states can a boolean have? And how many states can a bit have? If you get an answer other than two in either case let me know. Also, can you name another Java primitive type with only two states? – Elliott Frisch Jan 09 '19 at 00:26
  • @ElliottFrisch You are right by saying `boolean` is the ONLY primitive type with only two states, which is the same with `bit`. But my point is that even `boolean` only have two states, it cannot be stored in the memory with only one bit. – ZhaoGang Jan 09 '19 at 00:33

1 Answers1

0

Because Byte is the smallest addressable unit of memory in many computer architectures. You cann't address a single bit. There are also no such data type in java.

Frome wikipedia:

Historically, the byte was the number of bits used to encode a single character of text in a computer[1][2] and for this reason it is the smallest addressable unit of memory in many computer architectures.

ZhaoGang
  • 4,491
  • 1
  • 27
  • 39
  • [Bit-packing](https://www.cs.waikato.ac.nz/~tcs/COMP317/bitpacking.html) – Elliott Frisch Jan 11 '19 at 01:44
  • @ElliottFrisch With bit-packing we can pack multiple boolean values up into one or more Bytes in the server side, transform them via the net, finally get each of them in the client side. In that way we do optimize the network payload. But I suspect that the OP is talking about one single boolean value contained in a single http response, where bit-packing is not suitable. – ZhaoGang Jan 11 '19 at 02:21