user6796845
user6796845

Reputation:

Difference between Python and Java for Base64 decode

Here is a python code version:

 def decode(s):
  for i in range(len(s)):
      print compat_ord(s[i])

def compat_ord(c):
    if type(c) is int:
        return c
    else:
        return ord(c)
decode(base64.b64decode('NwXYSw8YI7nb2PnE8eJxVoLzuBQ81wjOXh4='.encode('ascii')))

output

55 5 216 75 15 24 35 185 219 216 249 196 241 226 113 86 130 243 184 20 60 215 8 206 94 30

My Java Version

byte[] s = Base64.getDecoder().decode("NwXYSw8YI7nb2PnE8eJxVoLzuBQ81wjOXh4=".getBytes("ascii"));
for(int i= 0;i<s.length;i++){
  System.out.println(s[i]);
}

Ouptput

55 5 -40 75 15 24 35 -71 -37 -40 -7 -60 -15 -30 113 86 -126 -13 -72 20 60 -41 8 -50 94 30

My Question

Why some values are same while some are not

Upvotes: 5

Views: 2776

Answers (1)

Axel
Axel

Reputation: 14159

byte in Java is 8 bit signed. So you will get negative values.

Change

System.out.println(s[i]);

to

System.out.println(s[i]&0xff);

to get the same values.

Update: I just saw that Java 8 introduced Byte.toUnsignedInt(). This is perhaps more readable:

System.out.println(Byte.toUnsignedInt(s[i]));

Upvotes: 7

Related Questions