Fwrite () in C & readInt () in Java is different in endianess

Source:

writing the number 27 using the fwrite () function.

int main()
{
  int a = 27;
  FILE *fp;
  fp = fopen("/data/tmp.log", "w");
  if (!fp)
     return -errno;

  fwrite(&a, 4, 1, fp);
  fclose();
  return 0;
}

Reading data (27) using DataInputStream.readInt ():

public int readIntDataInputStream(void)
{
   String filePath = "/data/tmp.log";
   InputStream is = null;
   DataInputStream dis = null;
   int k;

   is = new FileInputStream(filePath);
   dis = new DataInputStream(is);
   k = dis.readInt();
   Log.i(TAG, "Size : " + k);
   return 0;
}

O / r

Size : 452984832

Good thing in hexadecimal format 0x1b000000

0x1b- 27. But readInt () reads the data as large endian, while my native encoding is written as small endian., So, instead 0x0000001bI get 0x1b000000.

Do I understand correctly? Has anyone encountered this problem before?

+4
source share
2 answers

From Javadoc to readInt():

This method is suitable for reading bytes written by an writeIntinterface method .DataOutput

-, C, , java.nio. , , ByteBuffer, ByteOrder.LITTLE_ENDIAN, IntBuffer ByteBuffer, , ByteBuffer#getInt() .

, , @EJP , .

+2

:

  • , int 4, , 32- ints, int32_t uint32_t.

  • , . Windows . fopen("/data/tmp.log", "wb").

  • . , native endianness / endian API. , Java - -, C hton32(). , , , , / .

:

#include <endian.h>
#include <stdint.h>
#include <stdio.h>

int main(void) {
    uint32_t a = hton32(27);
    FILE *fp = fopen("/data/tmp.log", "wb");
    if (!fp) {
        return errno;
    }
    fwrite(&a, sizeof a, 1, fp);
    fclose();
    return 0;
}
0

Source: https://habr.com/ru/post/1663298/


All Articles