signed char的问题请教

mcmay 2014-11-14 08:29:12
各位达人,在Pointer on C中的习题里,有这样一个题:
Write a program that reads characters from the standard input and writes them to the standard output. It should also compute a checksum and write it out after the characters.
The checksum is computed in a signed char variable that is initialized to —1. As each character is read from the standard input, it is added to the checksum. Any overflow from the checksum variable is ignored. When all of the characters have been written, the checksum is then written as a decimal integer, which may be negative. Be sure to follow the checksum with a new‐line. On computers that use ASCII, running your program on a file containing the words ʺHello world!ʺ followed by a newline should produce the following output:
Hello world!
102

我不明白其中checksum是什么概念,然后看了答案代码。如下:
/* checksum.c */
/*
** This program copies its standard input to the standard output, and computes ** a checkusm of the characters. The checksum is printed after the input.
*/

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
int c;
char sum = -1;

/*
** Read the characters one by one, and add them to the sum.
*/
while((c = getchar()) != EOF){
putchar(c);
sum += c;
}
printf("%d\n", sum);

return EXIT_SUCCESS;
}


运行结果:
其中一次运行:

What does "checksum" mean anyway?
What does "checksum" mean anyway?
^Z
-40

另一次运行:

Gottya!
Gottya!
^Z
-94

编译运行后,那个checksum的值有时是个正数有时是个负数。不过不知为何会这样,这跟signed char的性质有关系吗?另外,这里的checksum是个什么概念?请达人帮忙解释一下,谢谢!
...全文
96 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
brookmill 2014-11-14
  • 打赏
  • 举报
回复
关于无符号数和有符号数,楼主可以搜一下“原码、反码、补码”
brookmill 2014-11-14
  • 打赏
  • 举报
回复
checksum就是“校验和”,自己搜一下应该能找到很多详细的介绍。 这里的算法很简单,就是把所有输入加起来,结果只保留最低的一个字节。这个字节如果按无符号数来解释就是unsigned char,取值在0~255,0~0xFF。如果按有符号数来解释,就是-128~127,其中最高位是符号位。 无符号 -- 有符号 0 -- 0 1 -- 1 ... 127 -- 127 128 -- -128 129 -- -127 ... 254 -- -2 255 -- -1

69,373

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧