Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert and compare byte array to int

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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

>Solution :

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 );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading