将4个字节转换为unsigned int

时间:2014-02-10 03:36:24

标签: c byte bit

如果有一个字符数组,如

char bytes[256]  = "10000011011110110010001101000011";

我想要这个的无符号值:2205885251

我正试图沿着这些方向做点什么

unsigned int arr[256];
for(int i = 0, k=0; i<256; i++, k++)
{
arr[k] = bytes[i]|bytes[i+1]<<8|bytes[i+2]<<16|bytes[i+3]<<24;
}

我获得了错误的价值:3220856520,是否有人可以指出我做错了什么?

3 个答案:

答案 0 :(得分:1)

#include <stdio.h>

char bytes[256]  = "10000011011110110010001101000011";

int main(void)
{
    unsigned int out;
    int i;

    for (out = 0, i = 0; i < 32; ++i)
        if (bytes[31 - i] == '1')
          out |= (1u << i);

    printf("%u\n", out);
    return 0;
}

Output is: 2205885251

答案 1 :(得分:0)

#include <stdio.h>

int main()
{
    char bytes[256]  = "10000011011110110010001101000011";
    unsigned int value = 0;
    for(int i = 0; i< 32; i++)
    {
        value = value *2  + (bytes[i]-'0');
    }
    printf("%u\n",value);
}

输出:2205885251

答案 2 :(得分:0)

char bytes[]  = "10000011011110110010001101000011";
unsigned int k;

k = strtoul(bytes, NULL, 2);
printf("%u \n", k);

瓦尔特