How to show float bytes

I personally use the show_bytes function 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 there are so many "f" before e6 and f0, and I use% .2x.

+5
source share
1 answer

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 type of the signed a pointer is raised to signed int by printf .

Format

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

  • First solution: the value is increased to signed int , but the past value is truncated in LSB.
  • Second example: the value is truncated by the type of the pointer, which is unsigned char .

Rule: in raw memory, always use unsigned types.

+6
source

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


All Articles