Home > Mobile >  How to convert and compare byte array to int
How to convert and compare byte array to int

Time:12-07

I'm trying to compare a byte array with a hex number, having a surprisingly hard time.

#include <stdio.h>

int main()
{
    int bytes[4] = { 0x7c, 0x71, 0xde, 0xbb };
    int number = 0x7c71debb;
    
    printf("%u\n", number);
    printf("%u\n", (int)*bytes);

    return 0;
}

I'm getting:

2087837371
124

I did some reading and I tried using memcpy as suggested in various places:

#include <stdio.h>
#include <string.h>

int main()
{
    int bytes[4] = { 0x7c, 0x71, 0xde, 0xbb };
    int number = 0x7c71debb;
    
    int frombytes;
    
    memcpy(&frombytes, bytes, 4);
    
    printf("%u\n", number);
    printf("%u\n", frombytes);

    return 0;
}

Still the same result:

2087837371
124

I mean, it's been like an hour if I got to be honest frustration is starting to get a hold of me.

It all started from me trying to do this:

if ((unsigned int)bytes == 0x7c71debb)

EDIT:

After switching bytes' type to char or uint8_t, here's what I'm getting:

#include <stdio.h>
#include <string.h>
#include <stdint.h>

int main()
{
    uint8_t bytes[4] = { 0x7c, 0x71, 0xde, 0xbb };
    int number = 0x7c71debb;
    
    int frombytes;
    
    memcpy(&frombytes, bytes, 4);
    
    printf("%u\n", number);
    printf("%u\n", (int)*bytes);
    printf("%u\n", frombytes);

    return 0;
}

Results:

2087837371
124
3151917436

CodePudding user response:

You are making two assumptions:

  • You're assuming int is exactly 32 bits in size.

    This might be correct, but it could be smaller or larger. You should use int32_t or uint32_t instead.

  • You're assuming a big-endian machine.

    If you are using an x86 or x86_64, this is incorrect. These are little-endian architectures. The bytes are ordered from least-significant to most-significant.

The following code avoids those assumptions:

int32_t frombytes =
   (uint32_t)bytes[0] << ( 8 * 3 ) |
   (uint32_t)bytes[1] << ( 8 * 2 ) |
   (uint32_t)bytes[2] << ( 8 * 1 ) |
   (uint32_t)bytes[3] << ( 8 * 0 );

(It looks a bit expensive, but your compiler should optimize this.)

CodePudding user response:

You can build the int using bitwise operators on the array values.

The below code, which assumes big-endian architecture and ints that are at least 4 bytes long, outputs:

2087837371
2087837371
#include <stdio.h>

int main()
{
    int bytes[4] = { 0x7c, 0x71, 0xde, 0xbb };
    int number = 0x7c71debb;
    int number2 = bytes[3] | bytes[2] << 8 | bytes[1] << 16 | bytes[0] << 24;
    
    printf("%u\n", number);
    printf("%u\n", number2);

    return 0;
}
  • Related