What is the best way to work around the fact that ALL Java bytes are signed?

In Java, there is no such thing as an unsigned byte.

Working with some low level code, occasionally you need to work with bytes that have unsigned values greater than 128, which causes Java to interpret them as a negative number due to the MSB being used for sign.

What’s a good way to work around this? (Saying don’t use Java is not an option)


When reading any single value from the array copy it into something like a short or an int and manually convert the negative number into the positive value it should be.

byte[] foobar = ..;
int value = foobar[10];
if (value < 0) value += 256 // Patch up the 'falsely' negative value

You can do a similar conversion when writing into the array.


Small modification to an XML document using StAX

I’m currently trying to read in an XML file, make some minor changes (alter the value of some attributes), and write it back out again.

I have intended to use a StAX parser ( to read in each event, see if it was one I wanted to change, and then pass it straight on to the StAX writer ( if no changes were required.

Unfortunately, that doesn’t look to be so simple – The writer has no way to take an event type and a parser object, only methods like writeAttribute and writeStartElement. Obviously I could write a big switch statement with a case for every possible type of element which can occur in an XML document, and just write it back out again, but it seems like a lot of trouble for something which seems like it should be simple.

Is there something I’m missing that makes it easy to write out a very similar XML document to the one you read in with StAX?


StAX works pretty well and is very fast. I used it in a project to parse XML files which are up to 20MB. I don’t have a thorough analysis, but it was definitely faster than SAX.

As for your question: The difference between streaming and event-handling, AFAIK is control. With the streaming API you can walk through your document step by step and get the contents you want. Whereas the event-based API you can only handle what you are interested in.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..