Java shift right outputting negative value
i'm really confused with, well it's best if I show my code first so here's what I got.
void dumpInt(int x) throws IOException {
if ( true ) {
//8388638
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
writer.writeByte(x&0xff);
writer.writeByte((x>>8)&0xff);
writer.writeByte((x >> 16) & 0xfff);
writer.writeByte((x>>24)&0xff);
outputStream.write(x & 0xff);
outputStream.write((x >> 8) & 0xff);
outputStream.write((x >> 16) & 0xff);
outputStream.write((x >> 24) & 0xff);
System.out.println((x >> 16) & 0xff);
if(x == 8388638){
String xz = "";
byte[]array = outputStream.toByteArray();
System.out.println(array[2]+" | " + (char)array[2]);
}
} else {
writer.writeInt(x);
}
}
this works fine but when I do dumpInt(8388638), I get some weird occurrences. writer.writeByte((x >> 16) & 0xfff)
writes -128 to the writer Im clueless as why that is.
The same thing happens for outputStream.write((x >> 16) & 0xff);
but when I run System.out.println((x >> 16) & 0xff);
it outputs 128(positive)
Does anybody know why this is and how I can correct it? (Sorry i'm somewhat experienced in java but im not the best by any means so if this is a really simple fix my bad)
from Recent Questions - Stack Overflow https://ift.tt/2S7DruM
https://ift.tt/eA8V8J
Comments
Post a Comment