-1

I have a byte for example:

"10000110" which is 97 in decimal.

I don't know the correct ordering, some places it is written "01100001", the point is that I'm speaking about the decimal number 97 which is stored in a single byte in our app.

We don't need bigger numbers than 100 in our app in this place of data and we would like to store an additional boolean data in the last (8th) bit in the corresponding byte, so..

  1. I would like to write a 0 in the 8th bit after I've read that bit for the boolean information.

So this way I will have my boolean data from the 8th bit, and after that I can write the 8th bit to zero, so I can read my byte to get the decimal number. (because we only use values from 0-100 the last bit should always be zero.)

I don't know if it is clear enough, please let me know if you have any questions.


So in short, my question is:

How could I write a 0 to the last bit of a byte in Java?

David Wasser
  • 93,459
  • 16
  • 209
  • 274
Adam Varhegyi
  • 11,307
  • 33
  • 124
  • 222
  • `"01100001" would be 97. Now you could only make the lsb zero as the hsb is already zero. – blackapps Mar 29 '22 at 15:29
  • 4
    value &= 0xFE . And the value would become 96. – blackapps Mar 29 '22 at 15:30
  • @blackapps It doesn't matter it is already zero, sometimes it will be one, as I described, it would be used to store a boolean value. – Adam Varhegyi Mar 29 '22 at 15:37
  • 3
    I dont understand your reaction. I told you how to make that bit zero and you dont even react on the given solution. – blackapps Mar 29 '22 at 15:39
  • @blackapps You wrote "And the value would become 96", but it is 97, why did you subtract one? – Adam Varhegyi Mar 29 '22 at 15:48
  • Err, what about that "prior research" thing?! Didn't it occur to you to do a quick search on "java binary operations" or "java setting bits"? – GhostCat Mar 29 '22 at 15:59
  • 1
    When you write "the last bit", this is confusing. For most people this would mean the low-order bit (binary 00000001 or hex 01). You are really referring to the high-order bit (binary 10000000 or hex 80 or decimal 128). – David Wasser Mar 29 '22 at 15:59
  • I removed the `android` tag as this code has absolutely nothing to do with Android. It is a generic Java question (although the question is Java-specific, the question and the answers apply to other programming languages as well) – David Wasser Mar 29 '22 at 16:01

1 Answers1

2

97 decimal is 61 (hexadecimal) or 1100001 (binary)

If you want to use the high-order bit (10000000 binary or 80 hex) to store other information, you can do this as follows:

byte b = 97;
// Set the high-order bit to 1
byte c = b | 0x80;

// Determine if the high-order bit is set or not
boolean bitIsSet = (c & 0x80) != 0;

// clear the high-order bit (remove the high-order bit to get the value)
byte d = c & 0x7F;

I hope this is clear and answers your question.

David Wasser
  • 93,459
  • 16
  • 209
  • 274