Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show bytes of float

Tags:

c

I personally use a function show_bytes as follows:

#include<stdio.h>
typedef char *byte_pointer;

void show_bytes (byte_pointer x)
{
        int length = sizeof(float);
        int i;
        for(i = 0;i <length;i++)
        {
                printf("%2x",*(x+i));
                printf("\n");
        }
}

int main()
{
        float obj;
        printf("please input the value of obj:");
        scanf("%f",&obj);
        show_bytes((byte_pointer) &obj);
}

when i input 120.45,which should be 0x42f0e666

please input the value of obj:120.45
66
ffffffe6
fffffff0
42

why so many 'f' before the e6 and f0 while i use %.2x.

like image 721
Sky_Sun Avatar asked Jan 28 '16 09:01

Sky_Sun


People also ask

Is float always 4 bytes?

Yes it has 4 bytes only but it is not guaranteed.

Why is float 4 bytes?

A 4‑byte floating point field is allocated for it, which has 23 bits of precision. float(41) defines a floating point type with at least 41 binary digits of precision in the mantissa. A 8‑byte floating point field is allocated for it, which has 53 bits of precision.

How many bytes are used by float?

Single-precision floating-point format (sometimes called FP32 or float32) is a computer number format, usually occupying 32 bits in computer memory; it represents a wide dynamic range of numeric values by using a floating radix point.


1 Answers

Your function should be:

void show_bytes (byte_pointer x)
{
   int i;
   for(i = 0; i <sizeof(float); i++)
   {
      printf("0x%2X\n", (unsigned int)(*(x++) & 0xFF));
   }
}

or

typedef uint8_t *byte_pointer;

void show_bytes (byte_pointer x)
{
   int i;
   for(i = 0; i <sizeof(float); i++)
   {
      printf("0x%2X\n", *(x++));
   }
}

In your code the problem is that the pointer type is signed an is promoted to signed int by printf.

%2X format does not limit the output digit, tells only to printf that the result string must be at least 2 characters long.

  • First solution: the value is promoted to signed int but the passed value is truncated to the LSB.
  • Second example: value is truncated by the type of pointer, that is unsigned char.

The rule is: to raw access memory, always use unsigned types.

like image 179
LPs Avatar answered Sep 25 '22 20:09

LPs