I have this code:
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;
}
Output when I run it:
port_rc: 1
length_rc: -1
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?
Thanks.
答案 0 :(得分:3)
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
.
I suggest not using sprintf()
to store numbers into the buffer. Declare it as:
unsigned char buffer[127];
Then you can do:
buffer[0] = port;
buffer[1] = length;
snprintf((char *)(buffer + 2), sizeof buffer - 2, "%s", record);
答案 1 :(得分:1)
“不过,在判断这种“解决方案”时要。
简而言之,根本的问题(在您的原始帖子中)是变量port_rc
和length_rc
应该被声明为 unsigned 整数。您不希望将诸如$FF
之类的值错误地“符号扩展”成为$FFFFFFFF == -1
...
您的“解决方案”与原始解决方案有很大不同,因为如您所见,它现在既存储在buffer[0]
和buffer[1]
中,又存储在中,然后检索并检查这些值!
答案 2 :(得分:0)
解决方案:
int main(){
unsigned 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);
}
buffer[0] = port;
buffer[1] = length;
snprintf((char *)(buffer), sizeof buffer - 2, "%c%c%s", port,length,record);
int port_rc = buffer[0];
int length_rc = buffer[1];
char char_first = buffer[2];
printf("port_rc: %d\n",port_rc);
printf("length_rc: %d\n",length_rc);
printf("char_first: %c\n",char_first);
return 0;
}
退货:
port_rc: 1
length_rc: 255
char_first: $