• Post Reply Bookmark Topic Watch Topic
  • New Topic

Unsigned byte in Java ?  RSS feed

 
Vinicius Alves
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm doing a communication with a printer , and now I need to write to the serialPort , but studying I saw that java only has signed bytes except for the char data type , how can I build a byte array and one of the elements to be an unsigned byte ?
it has to be byte array because I need to write it with an OutputStream or DataOutputStream.
I tried to write as a char array but it didn't work.
thank's !
 
Henry Wong
author
Sheriff
Posts: 22853
119
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vinicius Alves wrote:how can I build a byte array and one of the elements to be an unsigned byte ?


Just use an signed byte array -- it should work. It's all bits over the wire, and 8 bits is 8 bits regardless of whether it is signed or unsigned.

Now, to get a unsigned byte to and from a signed byte element does require special handling. You can't assign an unsigned byte value (assume short or int) to a signed byte, you need to AND out the higher order bits, and OR it into place. You can't assign an signed byte to a unsigned byte value (again assume or or int); actually you can, but then you need to AND out the higher order bits.

Henry
 
Rob Spoor
Sheriff
Posts: 20898
81
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Henry is right: bitwise, there is no difference between signed 255 and unsigned -1; both are 1111 1111 in binary.
 
Vinicius Alves
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Henry , it worked here !
I thought there would be difference between signed and unsigned byte after written with the OutputStream !
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!