如何获得以字节为单位的浮点数? [英] How to get float in bytes?

查看:61
本文介绍了如何获得以字节为单位的浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 HIDAPI 将一些数据发送到USB设备.此数据只能作为 byte 数组发送,我需要在此数据数组内发送一些float数字.我知道浮点数有4个字节.所以我认为这可能有效:

I am using the HIDAPI to send some data to a USB device. This data can be sent only as byte array and I need to send some float numbers inside this data array. I know floats have 4 bytes. So I thought this might work:

float f = 0.6;
char data[4];

data[0] = (int) f >> 24;
data[1] = (int) f >> 16;
data[2] = (int) f >> 8;
data[3] = (int) f;

后来我要做的就是:

g = (float)((data[0] << 24) | (data[1] << 16) | (data[2] << 8) | (data[3]) );

但是测试表明,像data[0] = (int) f >> 24;这样的行总是返回0.我的代码有什么问题以及如何正确执行此操作(即,将float内部数据分解为4 char字节,然后在以后重建相同的float)?

But testing this shows me that the lines like data[0] = (int) f >> 24; returns always 0. What is wrong with my code and how may I do this correctly (i.e. break a float inner data in 4 char bytes and rebuild the same float later)?

编辑:

我能够使用以下代码完成此任务:

I was able to accomplish this with the following codes:

float f = 0.1;
unsigned char *pc;
pc = (unsigned char*)&f;

// 0.6 in float
pc[0] = 0x9A;
pc[1] = 0x99;
pc[2] = 0x19;
pc[3] = 0x3F;

std::cout << f << std::endl; // will print 0.6

*(unsigned int*)&f = (0x3F << 24) | (0x19 << 16) | (0x99 << 8) | (0x9A << 0);

我知道memcpy()是一种更清洁"的方式,但是我认为这种方式会更好一些.

I know memcpy() is a "cleaner" way of doing it, but this way I think the performance is somewhat better.

推荐答案

您可以这样做:

char data[sizeof(float)];


float f = 0.6f;

memcpy(data, &f, sizeof f);    // send data


float g;

memcpy(&g, data, sizeof g);    // receive data

为使此功能正常运行,两台机器都需要使用相同的浮点表示形式.

In order for this to work, both machines need to use the same floating point representations.

正如评论中正确指出的那样,您不一定需要执行额外的memcpy;相反,您可以将f 直接作为字符数组(具有任何符号).但是,您仍然必须在接收端执行memcpy,因为您可能将任意字符数组都视为浮点数!示例:

As was rightly pointed out in the comments, you don't necessarily need to do the extra memcpy; instead, you can treat f directly as an array of characters (of any signedness). You still have to do memcpy on the receiving side, though, since you may not treat an arbitrary array of characters as a float! Example:

unsigned char const * const p = (unsigned char const *)&f;
for (size_t i = 0; i != sizeof f; ++i)
{
    printf("Byte %zu is %02X\n", i, p[i]);
    send_over_network(p[i]);
}

这篇关于如何获得以字节为单位的浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆