繁体   English   中英

如何在Java中以无符号方式将字节数组转换为Base 64字符串?

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

我正在努力在C#和Java中获得相同的Base64字符串

我希望Java在转换为Base64时将字节视为无符号字节。

这是我的C#代码

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);
}

在Java中,我想为相同的long值获得相同的Base64

这是代码

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();
}

我尝试了注释方法和DatatypeConverter方法,但是得到了不同的String值。 是否有标准的JDK方法,还是应该编写自己的base64方法将字节视为无符号字节?

Base64转换位。 它不知道或不在乎您是将字节视为带符号的还是无符号的。 如果获得不同的值,则问题出在其他地方。

但是,由于要进行移位,因此需要使用零填充版本>>>而不是符号扩展>> 那可能是您问题的根源。

DatatypeConverter仍然是最简单的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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