酒鬼z

我自将心向明月,独卧沙场醉圆缺

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

比如
float <-> char[4]
double <-> char[8]
我尝试直接赋值失败,数据不对

 
  •  

贴个@李振春的简单方法:

  1. union{
  2. float f;
  3. int i;
  4. };
  5. union{
  6. double d;
  7. int64 i;
  8. };
  9. union{
  10. float f;
  11. char c[4];
  12. };

利用union的特性,后面的属性和第一个属性表示的意义相同。编译器帮助转换,很巧妙啊。

  •  

1 使用内存拷贝函数。
2 指针和非指针之间的赋值,通过指针类型进行转换:

  1. float f =0.1;
  2. char c[sizeof(float)];
  3. *((float*)c)= f;
  4. f =(float*)c;
评论 (0) • 链接 • 2011-12-01
 

char -> double

double get_double(unsigned char[] input,int index) {
double output;
double a = input[0];
for (int i=1;i<index;i++){
a = input[i] * pow(2,8*i);
output += a;
}
}

评论 (2) • 链接 • 2011-12-01
  • 0
    input[0]被丢掉了。 – magic 2011-12-02
  • 0
    运行得不到预期的结果:
    unsigned char[] input // -> unsigned char input[],
    output // 没初始化,
    而且要不要考虑大小端问题?
    – magic 2011-12-02
  •  

利用结构体的特性,直接内存拷贝结构体,在编译器中字节对齐统一。
struct sChar{
char a[8];
}

struct sInt{
int a;
int b;
int c;
int d;
}

struct sFloat{
float a;
float b;
float c;
float d;
}

struct sDouble{
double a;
double b;
}

struct sDouble{
int64 a;
}

转自:http://www.dewen.org/q/669
posted on 2013-05-22 18:59  酒鬼z  阅读(2029)  评论(0)    收藏  举报