0

I am using the folowing code in c#

var Bytes = Convert.FromBase64String(mystring);

and in the byte[] I get the following values: [3,221,235,121,20,212]

but when I run the same conversion in android using :

byte[] secretKeyByteArray=Base64.decode(mystring.getBytes("UTF-8"),Base64.DEFAULT);

I get these values:[3,-35,-21,121,20,-44]. From this what I understand is that android converts byte values greater than 200 to -ve. Any suggestions on how I can get the same byte array in android as I get in c# and vice versa. Also the reason as to why this happens?. Thanks.

1
  • Better use Base64.decodeFromString(). Commented Feb 26, 2015 at 20:43

2 Answers 2

1

Those values are the same. The difference is signed and unsigned integer. You could print the hex values to see. You should interpret the bytes as unsigned integer on Android too.

Sign up to request clarification or add additional context in comments.

3 Comments

can't interpret it as int as I am using this array in calculating hash of a key so I need it in that byte[] form.
You speak nonsense. As soon as you start to do calculations with that byte array you can interpret the bytes as signed integer or unsigned integer.
yep those values are infact same :) though I ended up doing what I wrote in my answer your answer pointed me in the correct direction
0

After doing research I found a better alternative not mentioned in context to this problem. The problem is that the byte in android has range of -128 to 127 and the byte in c# is of range 0-255. Thus they are not equivalent in their ranges. In short, android actually converts any value above 127 to its equivalent signed value and thus the disparity. Since for my problem I wanted a solution to provide similar output in both cases so for my purpose I used the below code in c#:

 var Bytes= Convert.FromBase64String(mystring);

            sbyte[] secSbytes = Array.ConvertAll(Bytes, b => (sbyte)b);

The sbyte in c# is equivalent to java's byte as its range is of -128 to 127. And this solved my problem. By using this code I get [3,-35,-21,121,20,-44] for both android and java.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.