简体   繁体   English

将 double 转换为 uint8_t*

[英]Convert double to uint8_t*

I have a function that accepts uint8_t* which is supposed to be a string.我有一个接受 uint8_t* 的函数,它应该是一个字符串。 I want to send a double to this function.我想向这个函数发送一个双精度值。 I have tried this code below but it doesn't work.我已经尝试过下面的代码,但它不起作用。

double a = 10.98     
uint8_t* p = (uint8_t*) &a;
printf("p: %u \n", p); 
send_data(p);

But This code below works, all I want is to replace the string "90" with a double variable ABOVE.但是下面的代码有效,我想要的只是用双变量 ABOVE 替换字符串“90”。

static const char *data[6];
data[0] = "90";
static uint8_t *test; 
test = ( unsigned char *) data[dataCounter] ;
send_data(test);

So what I mean by doesn't work is that the function send_data is supposed to send a string over bluetooth to a android phone.所以我的意思是不起作用的是函数 send_data 应该通过蓝牙将字符串发送到 android 手机。 If I do it like the first sample code, the string is passed correctly.如果我像第一个示例代码那样做,则字符串会正确传递。

Note: I think its possibly because of the difference in data types that is being passed to the second argument.注意:我认为这可能是因为传递给第二个参数的数据类型不同。 The function is expecting 3 arguments.该函数需要 3 个参数。

 static uint32_t send_data(uint8_t data[]){ 
     return ble_nus_string_send(&m_nus, data, 5);
 }

This is the function defintion:这是函数定义:

uint32_t ble_nus_string_send    (ble_nus_t * p_nus,uint8_t * p_string,
uint16_t    length 
)

There are two different things you might mean by "sending the double as a string". “将双精度作为字符串发送”可能意味着两种不同的含义。 You might mean "send the actual existing bytes of the double as an array of bytes" (in other words, send 4.5 as {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x40}), or you might mean "send a textual representation of the double as a string (IOW, send 4.5 as "4.5"). The former case would be:您可能的意思是“将 double 的实际现有字节作为字节数组发送”(换句话说,将 4.5 发送为 {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x40}),或者您的意思可能是“将 double 的文本表示作为字符串发送(IOW,将 4.5 发送为“4.5”)。前一种情况是:

double d = 4.5;
ble_nus_string_send(&m_nus, (uint8_t *)(&d), 8);

This is probably not what you want, since the app you are sending to must be expecting it the same way, with the same endianness, same floating point representation, etc. You probably want the second case:这可能不是您想要的,因为您要发送到的应用程序必须以相同的方式期待它,具有相同的字节序,相同的浮点表示等。您可能想要第二种情况:

double d = 4.5;
char temp[20];
snprintf(temp, 20, "%g", d);
ble_nus_string_send(&m_nus, (uint8_t *)temp, strlen(temp));

The data size is limited to 5 bytes in this function call: ble_nus_string_send(&m_nus, data, 5) , while a double is 8 bytes long.在此函数调用中,数据大小限制为 5 个字节: ble_nus_string_send(&m_nus, data, 5) ,而double长度为 8 个字节。 Change this to:将此更改为:

ble_nus_string_send(&m_nus, data, 8);

and this should work.这应该有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM