比如 float <-> char[4] double <-> char[8] 我尝试直接赋值失败,数据不对
贴个@李振春的简单方法:
- union{
- float f;
- int i;
- };
- union{
- double d;
- int64 i;
- };
- union{
- float f;
- char c[4];
- };
利用union的特性,后面的属性和第一个属性表示的意义相同。编译器帮助转换,很巧妙啊。
1 使用内存拷贝函数。 2 指针和非指针之间的赋值,通过指针类型进行转换:
- float f =0.1;
- char c[sizeof(float)];
- *((float*)c)= f;
- f =(float*)c;
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; } }
利用结构体的特性,直接内存拷贝结构体,在编译器中字节对齐统一。 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
|
unsigned char[] input // -> unsigned char input[],
output // 没初始化,
而且要不要考虑大小端问题? – magic 2011-12-02