[笔记]char* 转 unsigned char*

来源:互联网 发布:windows安装centos引导 编辑:程序博客网 时间:2024/06/07 05:18

众所周知

char a = -1;unsigned char b;b = static_cast<unsigned int>(a);
没有任何问题,因为char 和 unsigned char表示的bit位数一样,然而

char* a = "123";unsigned char* b;b = static_cast<unsigned char*>(a);
无法通过编译

原因在于char* 和unsigned char*是两种不同的类型

3.9.1 Fundamental types [basic.fundamental]1 Objects declared as characters char) shall be large enough to store any member of the implementation's basic character set. If a character from this set is stored in a character object, the integral value of that character object is equal to the value of the single character literal form of that character. It is implementation-defined whether a char object can hold negative values. Characters can be explicitly declared unsigned orsigned. Plain char, signed char, and unsigned char are three distinct types. A char, a signed char, and an unsigned char occupy the same amount of storage and have the same alignment requirements (basic.types); that is, they have the same object representation. For character types, all bits of the objectrepresentation participate in the value representation. For unsigned character types, all possible bit patterns of the value representation represent numbers. These requirements do not hold for other types. In any particular implementation, a plain char object can take on either the same values as a signed char or an unsigned char; which one is implementation-defined.
使用reinterpret_cast进行强制转换


原创粉丝点击