cirrusio
cirrusio

Reputation: 590

Convert integer to byte array produces unexepected results

OK...this seems like a fairly easy problem but I can't figure out what is going on here. I have the following code to convert an integer to a byte array and test the output:

#include <stdio.h>

void int2bytearray(char *byte_array, int size, int num)
{
    for (int i = 0; i < size; i++)
    {   
        byte_array[i] = (num >> 8*i) & 0xFF;
    }   
}

int main()
{
    int test_int = 657850;
    int size = sizeof(int);
    
    printf("Size is %d\n", size);
    printf("Size of char is %d\n", (int)sizeof(char));
    
    char test_array[size];
    
    printf("Size of first entry %d\n", (int)sizeof(test_array[0]));

    int2bytearray(test_array, size, test_int);
    
    for (int i=0; i < size; i++)
    {   
        printf("%#02x", test_array[i]);
    }   

    printf("\nFirst byte is %#.2X", test_array[0]);

    return 0;
}

I expect main to return an array of bytes, but the first "byte" appears to be a 32 bit integer.

Unfortunately, I get the following output:

Size is 4
Size of char is 1
Size of first entry 1
0xffffffba0x90xa00
First byte is 0XFFFFFFBA

Can someone tell me why this first byte is printing out as 0XFFFFFFBA? Why is it a 32-bit integer and not a byte as defined?

Upvotes: 0

Views: 140

Answers (1)

dbush
dbush

Reputation: 224082

The problem is related both to the type being used and how you're printing the values.

The first element in the array has value 0xBA which as a signed char is -70 in decimal. When this value is passed to printf it is converted to type int, so now you have a 32 bit value of -70 whose representation is 0XFFFFFFBA you then print it using %X it which prints an unsigned int in hex.

There are two ways to fix this.

First, change the type of test_array to unsigned char. Then the values stored will be positive and print correctly. The other option is to use %hhX as the format specifier which states to print the value as an unsigned char which will print the proper number of digits.

Upvotes: 3

Related Questions