自动转4B为float

z@z-Calistoga-ICH7M-Chipset:~/zfloatNumber$ echo -e "\x3a\x5a\x5a" | xxd | sed 's/ .*//g' | awk '{$1=""; print $0}' | sed 's/\([^ ][^ ]\)/\1 /g' | sed 's/^/.\/a.out/g' | xargs -i bash -c "{}"

0.000833

意思是:echo -e "\x3a\x5a\x5a" | xxd 生成4B,因为echo还带一个0x0a

sed 's/ .*//g' | awk '{$1=""; print $0}' 取出原始的数据,

sed 's/\([^ ][^ ]\)/\1 /g'两位加一个空格

sed 's/^/.\/a.out/g' 前面加上./a.out,意思是调用这程序,参数是4个B。

 | xargs -i bash -c "{}" 执行这个,相当于 ./a.out 3a 5a 5a 0a



反向也可以的,转float为4B:

z@z-Calistoga-ICH7M-Chipset:~/zfloatNumber$ echo 3.14 | xargs -i ./a.out {}

40 48 f5 c3

z@z-Calistoga-ICH7M-Chipset:~/zfloatNumber$ echo 3.1415 | xargs -i ./a.out {}

40 49 e 56

z@z-Calistoga-ICH7M-Chipset:~/zfloatNumber$ cat z.c

#include "stdio.h"

union zz {

  unsigned char ch[4];

  float f;

}z;

int main( int argc, char * argv[])

{

if( argc == 5)

{

  sscanf( argv[4], "%x", &z.ch[0]);

  sscanf( argv[3], "%x", &z.ch[1]);

  sscanf( argv[2], "%x", &z.ch[2]);

  sscanf( argv[1], "%x", &z.ch[3]);

  printf("%lf\n", (double)z.f);

}

if( argc == 2)

{

  sscanf( argv[1], "%f", &z.f);

  printf("%x %x %x %x\n", z.ch[3], z.ch[2], z.ch[1], z.ch[0]);

}

  return 0;

}

你可能感兴趣的:(自动转4B为float)