0

I have a byte b that in Java represents signed integers from -128 to +127. How do I convert it to represent only (positive) unsigned integers? I don't want to use int or long but a 1-byte representation and simply shift the bits in b

raff5184
  • 344
  • 1
  • 2
  • 15
  • 1
    There are no unsigned primitives in Java. What are you attempting to solve? (You may wind up using a `short` for this, in all honesty...) – Makoto Dec 13 '19 at 17:20
  • I am doing some operations on that byte and then I send the byte to other pieces of code in other languages (Python, C..) so I can't change the number of bits. Also, because of some operations I am doing, I can't have negative integers. So I basically need a mask or function that takes a number between -128 and 127 and converts it to a positive one. I could use an int or a long, but eventually I need to trim it into a byte – raff5184 Dec 13 '19 at 17:35
  • If you're just sending a byte, that's 8 bits - is it the Java application's responsibility to send across the right byte representation or the right *number*? In C you can get unsigned bytes, and in Python you could always apply the `0xFF` mask to a number to get what would *definitely* not be a byte. – Makoto Dec 13 '19 at 17:42
  • *You send the value to other pieces of code*. But the sign is determined by the HOB. So doesn't that depend on how the other languages interpret the group of 8 bits. In Java, if the sign is set it's negative. Besides, true unsigned values are different in how they are compared, not just how they look. – WJS Dec 13 '19 at 17:42
  • Basically what I am sending is a CRC code that has to be 1 byte long; and so the Java application is responsible to send the correct sequence of bits and shouldn't add more bits (which is what would happen if I sent an `int`). Moreover, in Java I need to do some operations on that byte as if I could interpret it as an unsigned (0-255, like other languages), but eventually still have an 8-bit representation For example: byte b = -120; // Unsigned-like operations. -120 should be +8 send(); – raff5184 Dec 13 '19 at 18:08
  • I still don't quite understand why you can't just do the math in an `int` and then send the low order byte. If you were doing this in just 8 bit space you would also loose those same bits that you mask off of an int. I have done linear checksums and frame check sequences for various projects and I never had any problems with using signed types. Can you provide a concrete example where the math is affected doing one way vs the other. – WJS Dec 13 '19 at 18:56
  • Sure. I calculate the CRC and I get a negative integer. I append the CRC to the message and then execute a standard ReedSolomon encoding algorithm. The operations have to be executed in a binary field, so my negative number throws an exception because the field accepts numbers in 0-255 – raff5184 Dec 13 '19 at 23:33

0 Answers0