-1

I'm assigned with a task to pass a byte containing all ones ( 11111111 ) from an Android device to a remote Bluetooth device. The remote device is being coded in C. Since we don't have unsigned representation in Java, I wanted to know if it's possible to send this specific byte. I've searched through different posts (i.e. this), but haven't yet found a good solution.

To be more clear: the remote Bluetooth device wants to see a byte with 8 bits, all have been set to ONE (as a part of its protocol).

Cœur
  • 37,241
  • 25
  • 195
  • 267
SahandY
  • 3
  • 3
  • It's always possible to "pretend" that Java's `byte`s are unsigned, but it gets pretty hard if you have to do math on them... – awksp May 31 '14 at 22:43
  • @user3580294 Do you have a link to somewhere which I could take a look at this trick? – SahandY May 31 '14 at 22:58
  • Not directly, unfortunately. Whether that technique would work depends on what you are doing with the bytes. Are you doing math with them, or are you doing something more like hard-coding the byte and sending that? – awksp May 31 '14 at 23:00
  • Also, if you're on Java 7, you can write numbers in plain binary using the `0b` prefix (e.g. `0b11111111` is a byte with all 1s) – awksp May 31 '14 at 23:23

1 Answers1

0
byte b = -1;

Test it:

StringBuilder sb = new StringBuilder("00000000");
for (int bit = 0; bit < 8; bit++) {
  if (((b >> bit) & 1) > 0) {
    sb.setCharAt(7 - bit, '1');
  }
}
System.out.println(sb.toString());
Michael Hopfner
  • 133
  • 1
  • 10
  • Thanks @Michael. It was really helpful, but once again, I need to convert sb to Byte, because we have to write it as a Byte on Bluetooth stream. And if I get bytes out of it, I won't get ONE's. Sorry if my question is very basic. – SahandY Jun 01 '14 at 18:55
  • sb is just for you to test it. byte b is what you'd write - a java byte -1 has all 8 bits set to one. – Michael Hopfner Jun 02 '14 at 03:16