why is the base64 encode java code doing this -
so i'm trying understand base64 encoding better , came across implementation on wikipedia
private static string base64encode(byte[] in) { stringbuffer out = new stringbuffer((in.length * 4) / 3); int b; (int = 0; < in.length; += 3) { b = (in[i] & 0xfc) >> 2; out.append(codes.charat(b)); b = (in[i] & 0x03) << 4; if (i + 1 < in.length) { b |= (in[i + 1] & 0xf0) >> 4; out.append(codes.charat(b)); b = (in[i + 1] & 0x0f) << 2; if (i + 2 < in.length) { b |= (in[i + 2] & 0xc0) >> 6; out.append(codes.charat(b)); b = in[i + 2] & 0x3f; out.append(codes.charat(b)); } else { out.append(codes.charat(b)); out.append('='); } } else { out.append(codes.charat(b)); out.append("=="); } } return out.tostring(); } and i'm following along , line:
b = (in[i] & 0xfc) >> 2; and don't it...why bitwise , 252 number shift right 2...wouldn't same if shifted byte without doing bitwise operation? example:
b = in[i] >> 2; say in[i] letter e...represented 101 or in binary 01100101. if shift 2 right 011001 or 25. if bitwise &
01100101 11111100 -------- 01100100 but shift going chop off last 2 anyway...so why bother doing it?
can clarify me please. thanks.
in in[i] >> 2, in[i] converted int first. if negative byte (with high bit set) converted negative int (with now-highest 24 bits set well).
in (in[i] & 0xfc) >> 2, in[i] converted int above, , & 0xfc makes sure bits reset 0.
you're partially right, in (in[i] & 0xff) >> 2 give same result. & 0xff common way convert byte non-negative int in range 0 255.
the way know sure why original developer used 0xfc, , not 0xff, ask them - speculate it's make more obvious bits being used.
Comments
Post a Comment