I have one String like "01030920316".
when i am going to convert this string in long and then convert in bytes then its given below output for java
output in java : Tag in bytes : 0, 0, 0, 0, 61, 114, -104, 124
same thing i do in C when i get this output
output in C : Tag in bytes : 124,152,114,61,0,0,0,0
Here I understand the different between -104 and 152 because of signed and unsigned but why 0’s at first in java and in C at last. for this behavior i am getting problem when my this bytes goes to C program side for verification.
Please explain me the where problem occurs.
Java program :
final byte[] tagBytes = ByteBuffer.allocate(8)
.putLong(Long.parseLong("01030920316")).array();
System.out.println("Tag in bytes >> " + Arrays.toString(tagBytes));
C program :
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
/** To access long long values as a byte array*/
typedef union uInt64ToByte__
{
uint64_t m_Value;
unsigned char m_ByteArray[8];
}uInt64ToByte;
int main()
{
uInt64ToByte longLongToByteArrayUnion;
longLongToByteArrayUnion.m_Value = atoll("01030920316");
printf("%d,%d,%d,%d,%d,%d,%d,%d",longLongToByteArrayUnion.m_ByteArray[0],longLongToByteArrayUnion.m_ByteArray[1],longLongToByteArrayUnion.m_ByteArray[2],longLongToByteArrayUnion.m_ByteArray[3],longLongToByteArrayUnion.m_ByteArray[4],longLongToByteArrayUnion.m_ByteArray[5],longLongToByteArrayUnion.m_ByteArray[6],longLongToByteArrayUnion.m_ByteArray[7]);
return 0;
}
Strings are simply differently stored in Java and C. You have to remember that applications written in C are native and Java applications are run in Java Virtual Machine. Java byte code is platform independent and this is why your Java code would act the same on all operating systems / processor architectures. On the other hand the order of stored characters might be different in C (edit: on different architectures)
Edit2: Let’s say we have a number 109 which is 1101101 binary. Why? 1 * 64 + 1 * 32 + 0 * 16 + 1 * 8 + 1 * 4 + 0 * 2 + 1 * 1 = 109. The most left bit is called “the most significant” because it’s weight is the biggest (2^6 = 64) and the most right bit is called “the least significant” because it’s weight is the smallest (only 1). 109 is quite boring because it can be stored in a single byte. Let’s assume that we have something bigger like: 1000 which is 00000011 11101000 binary. It is stored in two bytes (let’s say X and Y). Now we can save that number as XY (big-endian) or YX (little-endian). In big-endian the first byte (with the lowest address) is the most significant byte. In little-endian the first byte is the least significant byte. x86 is little-endian and JVM is big-endian. This is why the outputs are different.