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("
");

                printf("0x%02x ", p[i]);
        }
        printf("

");
}
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
", a);
  //printf("%p
", a+1);
  //printf("%p
", a+5);
  //printf("0x%02x
", a);
  //print_hex(a);
  //printf("%015X
", 0xa3);
  float b = 1234.3;
  byte a[4];
  float2Bytes(a, b);
  printf("%x
", a[0]);
  printf("%x
", a[1]);
  printf("%x
", a[2]);
  printf("%x
", a[3]);
  //printf("a=%x
", b);
  //printf("a=%x
", a[0]);
  //printf("a=%4d
", b);
  //printf("a=%2d
", b);
}
                                                                               

  

原文地址:https://www.cnblogs.com/oxspirt/p/13999485.html