如何获得浮字节? [英] How to get float bytes?

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

问题描述

我现在用的是HIDAPI一些数据发送到USB设备。这个数据只能以字节数组发送,我需要发送这个数据数组里面的一些浮点数。我知道有花车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;

后来我不得不做的是:

And later all I had to do is:

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

但测试这说明我的线,如数据[0] =(int)的F&GT;&GT; 24; 总是返回 0 。有什么不对我的code,我怎么可能正确地做到这一点(即4个字节字符打破浮动内部数据,后来重建同一浮动)?

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)?

编辑:

我可以用下面的codeS做到这一点:

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.

推荐答案

您可以做到这一点是这样的:

You can do it like this:

char data[sizeof(float)];


float f = 0.6f;

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


float g;

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

为了这个工作,无论是机器都需要用同样的浮点再presentations。

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天全站免登陆