Question

I'm trying to create a Java program that writes files for my Adruino to read. The Arduino is a simple 8 bit microcontroller board, and with some extra hardware, can read text files from SD cards, byte by byte.

Turns out this was a whole lot harder than I thought. Firstly, there are no unsigned values in Java. Not even bytes for some reason! Even trying to set a byte to 0xFF gives a possible loss of precision error! This isn't very useful for this low-level code..

I would use ints and only use the positive values, but I like using byte overflow to my advantage in a lot of my code (though I could probably do this with modulus right after the math operation or something) and the biggest problem of all is I have no idea how to add an int as an 8 bit character to a String that gets written to a file later. Output is currently my biggest problem.

So, what would be the best way to do unsigned bit math based on some user input and then write those bits to a file as if each one was an ASCII character?

Was it helpful?

Solution

So, here's how it works.

You can treat Java bytes as unsigned. The only places where signs make a difference are

  • constants: just cast them to bytes
  • toString and parseInt
  • division
  • <, >, >=, <=

Operations where signedness does not matter:

  • addition
  • subtraction
  • multiplication
  • bit arithmetic (except for >>, just use >>> instead)

To convert bytes to their unsigned values as ints, just use & 0xFF, and to convert those to bytes use (byte).

Alternatively, if third-party libraries are acceptable, you might be interested in Guava's UnsignedBytes utility class. (Disclosure: I contribute to Guava.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top