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.
Yes it has 4 bytes only but it is not guaranteed.
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.
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.
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.
signed int
but the passed
value is truncated to the LSB.unsigned char
.The rule is: to raw access memory, always use unsigned types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With