Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between big and little endian floats?

For integer values, it is pretty straightforward the difference in little endian and big endian representation.

But it is not clear for me how a little endian float differs from a big endian float.

And finally, I would like to know which is more commonly used.

like image 699
André Puel Avatar asked Jan 29 '12 20:01

André Puel


People also ask

How do you know if its little endian or big-endian?

In little endian machines, last byte of binary representation of the multibyte data-type is stored first. On the other hand, in big endian machines, first byte of binary representation of the multibyte data-type is stored first.

What is little endian and big-endian with example?

Specifically, little-endian is when the least significant bytes are stored before the more significant bytes, and big-endian is when the most significant bytes are stored before the less significant bytes. When we write a number (in hex), i.e. 0x12345678 , we write it with the most significant byte first (the 12 part).

Does x86 use big-endian or little endian?

The x86 processors use little-endian byte ordering. The least significant byte (LSB) of an integer is stored at the lowest address of the integer. The most significant byte is stored at the highest address for data items in this processor.


2 Answers

Endianness just is a property of the bytes that make up a value that's composed from multiple bytes. Since a floating point number takes up 4 or 8 bytes endianness tells you in which order to read them. This is exactly the same as with integer values.

like image 187
Joey Avatar answered Oct 20 '22 03:10

Joey


Some sources say IEEE754 floats are always stored little-endian but The IEEE754 specification for floating point numbers simply doesn't cover the endianness problem and may vary from machine to machine. Here is sample code for floating point / byte array conversion:

#include <stdio.h>

int main(int argc, char** argv){
  char *a;
  float f = 3.14159;  // number to start with

  a = (char *)&f;   // point a to f's location

  // print float & byte array as hex
  printf("float: %f\n", f);
  printf("byte array: %hhX:%hhX:%hhX:%hhX\n", \
    a[0], a[1], a[2], a[3]);

  // toggle the sign of f -- using the byte array
  a[3] = ((unsigned int)a[3]) ^ 128;

  //print the numbers again
  printf("float: %f\n", f);
  printf("byte array: %hhX:%hhX:%hhX:%hhX\n", \
    a[0], a[1], a[2], a[3]);

  return 0;
}

It's output on a little-indian machine:

float: 3.141590 byte array: D0:F:49:40 float: -3.141590 byte array: D0:F:49:C0

Theoretically, on a big-endian machine the order of bytes would be reversed.

Reference: http://betterexplained.com/articles/understanding-big-and-little-endian-byte-order/

like image 29
Imran Rana Avatar answered Oct 20 '22 05:10

Imran Rana