简体   繁体   中英

C++ Send bytes from a string?

I am writing a little program that talks to the serial port. I got the program working fine with one of these lines;

unsigned char send_bytes[] = { 0x0B, 0x11, 0x00, 0x02, 0x00, 0x69, 0x85, 0xA6, 0x0e, 0x01, 0x02, 0x3, 0xf };

However the string to send is variable and so I want make something like this;

char *blahstring;
blahstring = "0x0B, 0x11, 0x00, 0x02, 0x00, 0x69, 0x85, 0xA6, 0x0e, 0x01, 0x02, 0x3, 0xf"
unsigned char send_bytes[] = { blahstring };

It doesn't give me an error but it also doesnt work.. any ideas?

a byte-string is something like this:

char *blahString = "\\x0B\\x11\\x00\\x02\\x00\\x69\\x85\\xA6\\x0E\\x01\\x02\\x03\\x0f"

Also, remember that this is not a regular string. It will be wise if you explicitly state it as an array of characters, with a specific size:

Like so:

unsigned char blahString[13] = {"\x0B\x11\x00\x02\x00\x69\x85\xA6\x0E\x01\x02\x03\x0f"};
unsigned char sendBytes[13];
memcpy(sendBytes, blahString, 13); // and you've successfully copied 13 bytes from blahString to sendBytes

not the way you've defined..

EDIT: To answer why your first send_bytes works, and the second doesn't is this: The first one, creates an array of individual bytes. Where as, the second one, creates a string of ascii characteres. So the length of first send_bytes is 13 bytes, where as the length of the second send_bytes is much higher, since the sequence of bytes is ascii equivalent of individual characters in the second blahstring .

blahstring is a string of characters.

1st character is 0, 2nd character is x, 3rd character is 0, 4th character is B etc. So the line

unsigned char send_bytes[] = { blahstring };

is an array (assuming that you preform a cast!) will have one item.

But the example that works is an array with the 1st character has a value 0x0B, 2nd character is of value 0x11.

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