40

Why is char by default in the range from -128 to 127 when it is supposed to represent a 'character' whose textual reprezentations are in the range from 0 to 255? In this sense I'd guess char should be unsigned by default, only if we intended to treat it only like 'numbers' we'd have to add 'signed' keyword. Therefore should I rather use unsigned char when I work with text files?

Also I don't understand why std::ofstream's read and write functions use char and not unsigned char when I need to work with binary files. There I don't care about signed-ness, do I? Moreover I've made successfuly a copy of a JPEG file using signed char like this:

//..open all streams..
char c;
while(input.peek()!=EOF){
    input.read(&c,1);   //std::ifstream input;
    output.write(&c,1); //std::ofstream output;
} 
//..close all streams..

Since it works I think the read reads an unsigned bytes (in image processing an unsigned char is commonly used) and sets c so that the value has some accidental signed interpretation in 2's complement. I need to create a histogram of values, but I get a runtime error because I use signed char as index. Isn't it rather stupid that I have to use some cast uc = (unsigned char)c;? when there could be at least a simple overload of read/write for unsigned char?

4

2 回答 2

55

它不是。

a 的符号char既不是 asigned char也不unsigned char是实现定义的。许多系统使其签名以匹配默认签名的其他类型(如int,但在某些系统上可能未签名。(比如说,如果你传递-funsigned-char给 GCC。)

于 2013-06-13T21:40:11.143 回答
36

这是您从标准中得到的答案:

3.9.1 基本类型[basic.fundamental]

1 声明为字符 char) 的对象应足够大以存储实现的基本字符集的任何成员。如果该集合中的字符存储在字符对象中,则该字符对象的整数值等于该字符的单个字符文字形式的值。char 对象是否可以保存负值是实现定义的。字符可以显式声明为无符号或有符号。普通字符、有符号字符和无符号字符是三种不同的类型。char、signed char 和 unsigned char 占用相同的存储量并且具有相同的对齐要求(basic.types);也就是说,它们具有相同的对象表示。对于字符类型,对象表示的所有位都参与值表示。对于无符号字符类型,值表示的所有可能的位模式都表示数字。这些要求不适用于其他类型。在任何特定实现中,普通 char 对象可以采用与带符号字符或无符号字符相同的值;哪一个是实现定义的。

于 2013-06-13T21:39:54.080 回答