十一月 2, 2012

C#中利用联合类型(union)做数值类型转换(byte[] to float)

Written by

在C/C++中,联合类型经常用来做数据类型转换,比如下面的联合类型可以直接将char数组转换成float类型:

#include <iostream.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

typedef union _UnFloat
{
float value;
char buff[4];
}UnFloat;
int main()
{
// convertor
UnFloat uf;
uf.value = 0;

float f = 3.1415626;

// byte array
char cf[4];
memset(cf, '\0', sizeof(cf));
memcpy(cf, &f, sizeof(cf));

// convert
memcpy(uf.buff, cf, sizeof(uf.buff));

// output
printf("The union converted float value is %f", uf.value);

char input[255];
gets(input);

return 0;
}

输出为:

The union converted float value is 3.141563

C#中没有联合类型(union),但是利用FieldOffset属性,就可以通过结构体定义联合类型:

using System.Runtime.InteropServices;

namespace FloatConvert
{
[StructLayout(LayoutKind.Explicit)]
public struct UnionFloat
{
[FieldOffset(0)]
public float value;
[FieldOffset(0)]
public byte buff0;
[FieldOffset(1)]
public byte buff1;
[FieldOffset(2)]
public byte buff2;
[FieldOffset(3)]
public byte buff3;
}

}

Category : .NetC#其他

Tags :

发表评论

电子邮件地址不会被公开。

Proudly powered by WordPress and Sweet Tech Theme