0

I have a pointer to an array of bytes (u8). I now have a function that takes a pointer of type int (unsigned int). What is an elegant way to accomplish this without creating a new array and converting each element?

I need to convert each byte to a single int. (i.e. {0x12, 0x34, 0x56} --> {0x00000012, 0x00000034, 0x00000056})

void external_function(unsigned int *val, int length)
{
    //Write values to ...
}

void my_function(u8 *array)
{
    int length = 10;

    //Need to convert *array to (unsigned int *)
    external_function(array, length);
}
2
  • C will do this for you if you do array[0] = input[0] and so on. Commented May 11, 2020 at 22:40
  • If external_function does not require all data in one call, you can do this without an array of int by defining a single int and iteratively assigning to it one value from the byte array and passing the address of the int to external_function with a length of one int. Commented May 11, 2020 at 22:58

1 Answer 1

1

What is an elegant way to accomplish this without creating a new array and converting each element?

There's not one. That's how you have to do it. The problem is that the 00 bytes between the elements you need just aren't there while it's a byte array.

Sign up to request clarification or add additional context in comments.

1 Comment

The reason why this is impossible is because memory layout, including the size, of the array element type is part of the binary interface of external_function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.