好好爱自己!

c语言,浮点数转byte array

参考: https://www.cnblogs.com/wdfrog/p/5391613.html

 

 

#include <stdio.h>
#include <string.h>
typedef  unsigned char byte;
void print_hex(const char *string)
{
        unsigned char *p = (unsigned char *) string;

        for (int i=0; i < strlen(string); ++i) {
                if (! (i % 16) && i)
                        printf("\n");

                printf("0x%02x ", p[i]);
        }
        printf("\n\n");
}
void float2Bytes(byte bytes_temp[4],float float_variable){
  union {
    float a;
    byte bytes[4];
  } thing;
  thing.a = float_variable;
  memcpy(bytes_temp, thing.bytes, 4);
}

int main() {

  //char a[10] ="abcdefghi";
  //printf("%p\n", a);
  //printf("%p\n", a+1);
  //printf("%p\n", a+5);
  //printf("0x%02x\n", a);
  //print_hex(a);
  //printf("%015X\n", 0xa3);
  float b = 1234.3;
  byte a[4];
  float2Bytes(a, b);
  printf("%x\n", a[0]);
  printf("%x\n", a[1]);
  printf("%x\n", a[2]);
  printf("%x\n", a[3]);
  //printf("a=%x\n", b);
  //printf("a=%x\n", a[0]);
  //printf("a=%4d\n", b);
  //printf("a=%2d\n", b);
}
                                                                               

  

posted @ 2020-11-18 14:07  立志做一个好的程序员  阅读(639)  评论(0编辑  收藏  举报

不断学习创作,与自己快乐相处