1

我正在编写一个与串行端口对话的小程序。我让程序在其中一条线路上运行良好;

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

但是要发送的字符串是可变的,所以我想做这样的事情;

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

它不会给我一个错误,但它也不起作用..有什么想法吗?

4

2 回答 2

7

一个字节串是这样的:

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

另外,请记住,这不是常规字符串。如果您明确地将其声明为具有特定大小的字符数组,那将是明智的:

像这样:

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

不是你定义的方式..

编辑:回答为什么你的第一个send_bytes有效,第二个无效:第一个,创建一个单独的字节数组。其中,第二个创建了一串 ascii 字符。所以 first 的长度send_bytes是 13 个字节,而 second 的长度send_bytes要高得多,因为字节序列是 ascii 等效于 second 中的单个字符blahstring

于 2013-02-01T05:26:52.750 回答
0

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.

于 2013-02-01T05:28:13.533 回答