java - parseInt on a string of 8 bits returns a negative value when the first bit is 1 -
i've got huge string of bits (with \n
in too) pass parameter method, should isolate bits 8 8, , convert them bytes using parseint()
.
thing is, every time substring of 8 bits starts 1, resulting byte negative number. example, first substring '10001101', , resulting byte -115. can't seem figure out why, can help? works fine other substrings.
here's code, if needed :
static string bitstobytes(string genestring) { string genestring_temp = "", sub; for(int = 0; < genestring.length(); = i+8) { sub = genestring.substring(i, i+8); if (sub.indexof("\n") != -1) { if (sub.indexof("\n") != genestring.length()) sub = sub.substring(0, sub.indexof("\n")) + sub.substring(sub.indexof("\n")+1, sub.length()) + genestring.charat(i+9); } byte octet = (byte) integer.parseint(sub, 2); system.out.println(octet); genestring_temp = genestring_temp + octet; } genestring = genestring_temp + "\n"; return genestring; }
in java, byte
signed type, meaning when significant bit set 1
, number interpreted negative.
this precisely happens when print byte here:
system.out.println(octet);
since printstream
not have overload of println
takes single byte, overload takes int
gets called. since octet
's significant bit set 1
, number gets sign-extended replicating sign bit bits 9..32, resulting in printout of negative number.
Comments
Post a Comment