简体   繁体   English

将 char* 的值设置为无符号 integer

[英]Setting the value of a char* to an unsigned integer

I have a very basic C question.我有一个非常基本的 C 问题。 For context, I am working on a Nordic microcontroller and looking at one of their sample projects.对于上下文,我正在研究 Nordic 微控制器并查看他们的示例项目之一。 The below function writes the value of value to the buffer and that data gets sent to the Bluetooth client.下面的 function 将 value 的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));
}

Now when I change one line to a hardcoded value:现在,当我将一行更改为硬编码值时:

const char *value = "A";

It works as expected.它按预期工作。 The first byte changes to 0x41 which is the ASCII value of 'A'.第一个字节变为 0x41,这是“A”的 ASCII 值。

Now what if I want to change the first byte to a number for example 32?现在,如果我想将第一个字节更改为数字(例如 32)怎么办? I tried:我试过:

const char *value = 0x20;

but the first byte was not 0x20.但第一个字节不是 0x20。 I am thinking this change messes with the address location instead of the value or something.我认为此更改会混淆地址位置而不是值或其他内容。

I am thinking this change messes with the address location instead of the value or something.我认为此更改会混淆地址位置而不是值或其他内容。

You are right.你是对的。 Doing const char *value = NUMBER you just assign that pointer some arbitrary address, which is not what you want.执行const char *value = NUMBER您只需为该指针分配某个任意地址,这不是您想要的。 What you want is to assign that pointer some known address, which points to some arbitrary data.您想要的是为该指针分配一些已知地址,该地址指向一些任意数据。

The simplest way to do this would be to directly allocate that data in the function's own stack, like this:最简单的方法是直接在函数自己的堆栈中分配该数据,如下所示:

const char value[] = {32};

The reason const char *value = "A";原因const char *value = "A"; works is because "A" is a string literal .有效是因为"A"是一个字符串文字 If you used const char *value = 'A';如果你使用const char *value = 'A'; you would have the same problem as your 0x20 , as this is a character literal .您会遇到与0x20相同的问题,因为这是一个字符文字

Another way to write this might be:另一种写法可能是:

const char A[2] = { 'A', '\n' };    // same as "A"

const char *value = A;

So if you just want this pointer to point to a single value you can do the same thing:所以如果你只是想让这个指针指向一个单一的值,你可以做同样的事情:

const char singleValue[1] = { 0x20 };

const char *value = singleValue;

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

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