c - How to show bytes of float -


i use function show_bytes 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 value of obj:");         scanf("%f",&obj);         show_bytes((byte_pointer) &obj); } 

when input 120.45,which should 0x42f0e666

please input value of obj:120.45 66 ffffffe6 fffffff0 42 

why many 'f' before e6 , f0 while use %.2x.

your function should be:

void show_bytes (byte_pointer x) {    int i;    for(i = 0; <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; <sizeof(float); i++)    {       printf("0x%2x\n", *(x++));    } } 

in code problem pointer type signed promoted signed int printf.

%2x format not limit output digit, tells printf result string must at least 2 characters long.

  • first solution: value promoted signed int passed value truncated lsb.
  • second example: value truncated type of pointer, unsigned char.

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


Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -

Python Pig Latin Translator -