无符号字符和 sprintf() C [英] unsigned characters and sprintf() C

查看:64
本文介绍了无符号字符和 sprintf() C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码:

int main(){

char buffer[1024];
char port = 1;
int length = 255;
char * record = "$TAG ,0 ,89 ,0, 1\n";

if(length < 0 || length > 255){
    printf("Error - length out of range for an unsigned char.\n");
    exit(1);
}

snprintf(buffer, 1024, "%c%c%s", port, (unsigned char) length, record);

int port_rc     = buffer[0];
int length_rc   = buffer[1]; 

printf("port_rc: %d\n",port_rc);
printf("length_rc: %d\n",length_rc);

return 0;

}

运行时的输出:

port_rc: 1length_rc: -1

我想我在 snprintf() 方面遗漏了一些东西,因为在读取它创建的数组时我没有看到 255 值.我的猜测是 snprintf() 正在将变量 'length' 提升为 int 或其他东西.有谁知道我如何实现这一目标?

I think I am missing something here in terms of snprintf() as i'm not seeing the 255 value when reading the array it created back. My guess is that snprintf() is promoting the variable 'length' to an int or something. Does anyone know how I can achieve this?

谢谢.

推荐答案

我不认为您可以使用 sprintf()255 存储到缓冲区中.sprintf() 的缓冲区参数是一个 char 数组.char 默认是 signed 还是 unsigned 是实现定义的;请参阅默认情况下char是有符号还是无符号?.如果 255 大于 CHAR_MAX,尝试存储 255 会导致未定义的行为;如果实现默认为 signed 那么 CHAR_MAX 可能是 127.

I don't think you can use sprintf() to store 255 into the buffer. The buffer argument to sprintf() is a char array. Whether char is signed or unsigned by default is implementation-defined; see Is char signed or unsigned by default?. If 255 is greater than CHAR_MAX, trying to store 255 results in undefined behavior; if the implementation defaults to signed then CHAR_MAX will probably be 127.

我建议不要使用 sprintf() 将数字存储到缓冲区中.声明为:

I suggest not using sprintf() to store numbers into the buffer. Declare it as:

unsigned char buffer[127];

然后你可以这样做:

buffer[0] = port;
buffer[1] = length;
snprintf((char *)(buffer + 2), sizeof buffer - 2, "%s", record);

这篇关于无符号字符和 sprintf() C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆