Convert "unsigned int" to vector of "unsigned char"?

Question:

I need to convert an unsigned int into a vector of unsigned char to later translate these addresses into binary, for a job that I need to simulate a virtual memory. Can someone explain to me how to do this?

Answer:

If I understand correctly, you want to reinterpret a vector of integers to a vector of "bytes". So, you can do it here:

#include <stdio.h>
#include <stdlib.h>

#define ASIZE(x) sizeof(x)/sizeof(x[0])

int main (void) {

    const unsigned int teste[5] = {300, 500, 900, 1100, 1300};
    unsigned char *buf = NULL;
    size_t jmp = 0;

    buf = malloc(ASIZE(teste));
    if (!buf) abort();

    for (size_t index = 0; index < ASIZE(teste); index++,jmp+=sizeof(int)) {
            buf[jmp] = teste[index] & 0x000000ff;
            buf[jmp+1] = (teste[index] & 0x0000ff00) >> 8;
            buf[jmp+2] = (teste[index] & 0x00ff0000) >> 16;
            buf[jmp+3] = (teste[index] & 0xff000000) >> 24;
            printf("%u - %u - %u - %u\n", buf[jmp+3], buf[jmp+2], buf[jmp+1], buf[jmp]);
    }

    return 0;
}

The code above makes use of bit manipulation. In case you don't know what this is, just take a look here: http://www.programiz.com/c-programming/bitwise-operators

Scroll to Top