2014-04-12 52 views
0

我用下面的代码将字符串转换成整数:将字符串转换成无符号整数

int main(){ 
const char* mystring="abcdefghijklmnop"; 

unsigned int* key = (unsigned int*)mystring; 
for(int i=0;i<2;i++) { 
    std::cout << i << ": " << key[i] << std::endl; 
} 
std::cout << std::endl << "Result for:" << mystring << std::endl; 
} 

结果:

0: 1684234849 
1: 1751606885 
2: 1818978921 
3: 1886350957 

Result for:abcdefghijklmnop 

正如你可以看到,它的工作真的很好,但只是直到编码不同的时刻,例如。对于像字符串:®_ďÚ.J.®—Mf3Lý!®(ASCII)

It returns: 

0: 3294604994 
1: 781894543 
2: 2931961418 
3: 1301577954 

Result for:®_ÄŹĂš.J.®—Mf3LĂ˝!® // <-- notice this, its totally different as the input (`®_ďÚ.J.®—Mf3Lý!®`) 

我试图设置编码在我的IDE(Netbeans的),但没有任何独到之处结果(见下面的Result for:),还有,我也尝试编译对ideone源.com,设置浏览器编码 - 不幸的是结果相同。有没有可能根据输入字符串编码生成real结果而不会搞乱它?也许还有其他的可能性来实现我想要的?

回答

1

您的IDE正在输入以UTF-8编码的字符。我通过从数字输出向后工作来验证这一点,它生成了®_ďÚ.J.®—M。顺便说一下,调用这个ASCII码是不准确的。

您的输出窗口正在使用不同的编码。看起来它是code page 1250 Central/Eastern European

+0

是的,你几乎是正确的,编码被设置为UTF8与BOM ...解决方案很简单 - 设置编码在每个cpp文件使用fe。 Notepad ++并在Netbeans中进行编译。 – Lucas