将 char* 的值设置为无符号整数
Setting the value of a char* to an unsigned integer
我有一道非常基础的 C 题。对于上下文,我正在研究 Nordic 微控制器并查看他们的示例项目之一。下面的函数将 value
的值写入缓冲区,并将数据发送到蓝牙客户端。
static ssize_t read_long_vnd(struct bt_conn *conn,
const struct bt_gatt_attr *attr, void *buf,
u16_t len, u16_t offset)
{
const char *value = attr->user_data;
return bt_gatt_attr_read(conn, attr, buf, len, offset, value,
sizeof(vnd_long_value));
}
现在,当我将一行更改为硬编码值时:
const char *value = "A";
它按预期工作。第一个字节变为 0x41,这是 'A'.
的 ASCII 值
现在,如果我想将第一个字节更改为一个数字(例如 32)怎么办?我试过了:
const char *value = 0x20;
但第一个字节不是 0x20。我认为此更改会混淆地址位置而不是值或其他内容。
I am thinking this change messes with the address location instead of the value or something.
你是对的。做 const char *value = NUMBER
你只是给那个指针分配了一个任意地址,这不是你想要的。您想要的是为该指针分配一些已知地址,该地址指向一些任意数据。
最简单的方法是直接在函数自己的堆栈中分配数据,如下所示:
const char value[] = {32};
const char *value = "A";
起作用的原因是因为 "A"
是 string literal. If you used const char *value = 'A';
you would have the same problem as your 0x20
, as this is a character literal。
另一种写法可能是:
const char A[2] = { 'A', '\n' }; // same as "A"
const char *value = A;
所以如果你只是想让这个指针指向一个单一的值,你可以做同样的事情:
const char singleValue[1] = { 0x20 };
const char *value = singleValue;
我有一道非常基础的 C 题。对于上下文,我正在研究 Nordic 微控制器并查看他们的示例项目之一。下面的函数将 value
的值写入缓冲区,并将数据发送到蓝牙客户端。
static ssize_t read_long_vnd(struct bt_conn *conn,
const struct bt_gatt_attr *attr, void *buf,
u16_t len, u16_t offset)
{
const char *value = attr->user_data;
return bt_gatt_attr_read(conn, attr, buf, len, offset, value,
sizeof(vnd_long_value));
}
现在,当我将一行更改为硬编码值时:
const char *value = "A";
它按预期工作。第一个字节变为 0x41,这是 'A'.
的 ASCII 值现在,如果我想将第一个字节更改为一个数字(例如 32)怎么办?我试过了:
const char *value = 0x20;
但第一个字节不是 0x20。我认为此更改会混淆地址位置而不是值或其他内容。
I am thinking this change messes with the address location instead of the value or something.
你是对的。做 const char *value = NUMBER
你只是给那个指针分配了一个任意地址,这不是你想要的。您想要的是为该指针分配一些已知地址,该地址指向一些任意数据。
最简单的方法是直接在函数自己的堆栈中分配数据,如下所示:
const char value[] = {32};
const char *value = "A";
起作用的原因是因为 "A"
是 string literal. If you used const char *value = 'A';
you would have the same problem as your 0x20
, as this is a character literal。
另一种写法可能是:
const char A[2] = { 'A', '\n' }; // same as "A"
const char *value = A;
所以如果你只是想让这个指针指向一个单一的值,你可以做同样的事情:
const char singleValue[1] = { 0x20 };
const char *value = singleValue;