简体   繁体   中英

Convert double to uint8_t*

I have a function that accepts uint8_t* which is supposed to be a string. 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.

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. 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.

 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 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. Change this to:

ble_nus_string_send(&m_nus, data, 8);

and this should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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