0

I am struggling to get the same Base64 string in both C# and Java

I want Java to treat bytes as unsigned ones when converting to Base64.

Here's my C# code

private static void Main(string[] args)
{
    long baseTimeStamp = 1501492600;
    byte[] bytes = BitConverter.GetBytes(baseTimeStamp * 114);

    for (int i = 0; i < bytes.Length; i++)
    {
        bytes[i] = (byte)(bytes[i] >> 2);
    }

    string base64 = Convert.ToBase64String(bytes);

    Console.WriteLine(base64);
}

In Java, I want to get the same Base64 for the same long value

Here's the code

public static void main(String[] args) {
    long myLong = 1501492600;

    byte[] bytes = longToBytes(myLong);

    for(int i = 0; i < bytes.length / 2; i++)
    {
        int temp = bytes[i];
        bytes[i] = bytes[bytes.length - i - 1];
        bytes[bytes.length - i - 1] = (byte) temp;

        bytes[i] = (byte)((bytes[i] >> 2));
    }

    System.out.println(DatatypeConverter.printBase64Binary(bytes));
}

private static byte[] longToBytes(long x) {
    ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
    buffer.putLong(x);
    return buffer.array();
}

I tried both the commented way, and the DatatypeConverter way, but I get different String values. Is there a standard JDK way, or should I write my own base64 method to treat bytes as unsigned ones?

4
  • Base64 does not care about "signed" or "unsigned". I guess the problem is that you are converting diffferent byte-arrays, so you might find the source of the problem in longToBytes - whatever that does. Commented Jul 31, 2017 at 11:45
  • Since >> in C# is logical shift, you need to do bytes[i] = (byte)((bytes[i] & 0xff) >> 2) in order to do the same with Java. Commented Jul 31, 2017 at 12:02
  • I tried that our, but it works only when I assign to an int, when I assign back to a byte, I lose the unsigned behavior again Commented Jul 31, 2017 at 12:06
  • 1
    Try adding buffer.order(ByteOrder.LITTLE_ENDIAN) before buffer.putLong and see if things improve.... Commented Jul 31, 2017 at 14:03

1 Answer 1

1

Base64 converts bits. It doesn't know or care about whether you think of the bytes as signed or unsigned. If you're getting different values, the problem is somewhere else.

However, since you're doing bit shifting, you need to use the zero-fill version >>> instead of the sign extend >>. That may be the source of your problem.

DatatypeConverter is still the easiest way to go.

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

1 Comment

you're right, the conversion is right, the problem lies in shifting, although there's no difference in my case between >> and >>>

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.