Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Reading Bits from Input Stream Stream  RSS feed

 
Uma Bandaru
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can any body tell me how to read data bit-by-bit from a Java input stream (Sockets, to be specific)?
Thanks in advance.
 
Rob Spoor
Sheriff
Posts: 20893
81
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Call read() until it returns -1?

Oh wait, bit-by-bit. read() returns byte-by-byte. To get individual bits from a byte you need to use bitmasks. For instance, the 4th bit can be queried using (b & (1 << 3)). If that's equal to 1 << 3 then its set, otherwise it's 0 and is not set.


And in case you don't know (showing only the least significant 8 bits):
1 << 0 == 1 (0000 0001)
1 << 1 == 2 (0000 0010)
1 << 2 == 4 (0000 0100)
1 << 3 == 8 (0000 1000)
1 << 4 == 16 (0001 0000)
1 << 5 == 32 (0010 0000)
1 << 6 == 64 (0100 0000)
1 << 7 == 128 (1000 0000), equivalent to a byte value of -127
 
Uma Bandaru
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was wondering if there is anything in the API. But if there isn' t any, then I guess this is the best way to go about: Mask and shift. Thanks a lot.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!