简体   繁体   中英

How to convert byte array to Base 64 string in unsigned way in java?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM