user1720205
user1720205

Reputation:

Converting 4 bytes to unsigned int

If one has a character array such as

char bytes[256]  = "10000011011110110010001101000011";

I want to unsigned value of this which would be : 2205885251

I'm trying to do something along these lines

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;
}

I am obtaining the wrong value: 3220856520, can anyone point out what I am doing wrong?

Upvotes: 0

Views: 2100

Answers (3)

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

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

valter

Upvotes: 0

michaeltang
michaeltang

Reputation: 2898

#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);
}

it outputs: 2205885251

Upvotes: 0

David Schwartz
David Schwartz

Reputation: 182761

#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

Upvotes: 1

Related Questions