简体   繁体   English

您可以将带符号的char数组转换为无符号的整数吗?

[英]Can you convert a signed char array to an unsigned integer?

I have a unsigned int that was converted to a signed char like this 我有一个无符号的int,它被转换成这样的带符号的char

  unsigned int b = 128;
  char a[4];    

  a[0] = b >> 24;
  a[1] = b >> 16;
  a[2] = b >> 8;
  a[3] = b >> 0;

Without knowing what value of b is, can I get back the number? 不知道b值是什么,我可以取回这个数字吗? The method below fails for numbers greater than 128. It seems like there is some ambiguity to getting the number back from the array. 对于大于128的数字,下面的方法将失败。似乎从数组中取回数字有些模棱两可。

  unsigned int c = 0;  
  c += a[0] << 24;
  c += a[1] << 16;
  c += a[2] << 8;
  c += a[3];

  cout<<c<<endl;
unsigned int c = ((a[0] << 24) & 0xFF000000U)
               | ((a[1] << 16) & 0x00FF0000U)
               | ((a[2] <<  8) & 0x0000FF00U)
               | ( a[3]        & 0x000000FFU);

or 要么

unsigned int c = unsigned(a[0]) << 24
               | unsigned(a[1]) << 16
               | unsigned(a[2]) <<  8
               | unsigned(a[3]);

Converting signed to unsigned is not advised. signedunsigned是不明智的。 If you do want to do it, you have to do it manually. 如果您确实想这样做,则必须手动进行。 Not easy, AFAIK. 不容易,AFAIK。

Have a look at this question. 看看这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM