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?
longToBytes- whatever that does.>>in C# is logical shift, you need to dobytes[i] = (byte)((bytes[i] & 0xff) >> 2)in order to do the same with Java.buffer.order(ByteOrder.LITTLE_ENDIAN)beforebuffer.putLongand see if things improve....