Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert little Endian file into big Endian

Tags:

java

how can i convert a liitle Endian binary file into big Endian binary file. i have a binary binary written in C and i am reading this file in Java with DataInputStream which reads in big endian format.i also had a look on ByteBuffer class but have no idea how to use it to get my desired result. please help.

thanks alot

like image 682
sajjoo Avatar asked Aug 09 '10 08:08

sajjoo


People also ask

How do you do an endian swap?

To do this, we shift the rightmost 8 bits by 24 to the left so that it becomes the leftmost 8 bits. We left shift the right middle byte by 16 (to store it as the left middle byte) We left shift the left middle byte by 8 (to store it as the right muddle byte) We finally left shift the leftmost byte by 24 to the left.

What is the difference between a big endian file and a little endian file?

Big-endian is an order in which the "big end" (most significant value in the sequence) is stored first, at the lowest storage address. Little-endian is an order in which the "little end" (least significant value in the sequence) is stored first.

Is PNG big endian?

PNG files store 16-bit pixels in network byte order (big-endian, ie most significant bytes first).

What is better big endian or little endian?

The advantages of Big Endian and Little Endian in a computer architecture. According to Wiki, Big endian is “the most common format in data networking”, many network protocols like TCP, UPD, IPv4 and IPv6 are using Big endian order to transmit data. Little endian is mainly using on microprocessors.


1 Answers

Opening NIO FileChannel:

FileInputStream fs = new FileInputStream("myfile.bin");
FileChannel fc = fs.getChannel();

Setting ByteBuffer endianness (used by [get|put]Int(), [get|put]Long(), [get|put]Short(), [get|put]Double())

ByteBuffer buf = ByteBuffer.allocate(0x10000);
buf.order(ByteOrder.LITTLE_ENDIAN); // or ByteOrder.BIG_ENDIAN

Reading from FileChannel to ByteBuffer

fc.read(buf);
buf.flip();
// here you take data from the buffer by either of getShort(), getInt(), getLong(), getDouble(), or get(byte[], offset, len)
buf.compact();

To correctly handle endianness of the input you need to know exactly what is stored in the file and in what order (so called protocol or format).

like image 98
bobah Avatar answered Oct 18 '22 10:10

bobah