Convert "unsigned int" into "unsigned char" vector?

5

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

    
asked by anonymous 24.06.2015 / 19:25

3 answers

1

If I get it right, you want to reinterpret a vector of integers for 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 above code makes use of bit manipulation. If you do not know what this is, just have a look here: link

    
25.06.2015 / 13:09
1

The answer you chose as the best might be responsible for undefined behavior ie you can change pieces of memory that do not belong to causing crashes or bugs. If it were me you would use a [union] [2] to convert, easier, faster and more feasible.

See the example here:

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

int main (void) {

   typedef union _Conversor
   {
       unsigned int inicial; //Valor que vai armazenar
       unsigned char leitor[4];//Para ler todos os bytes unsigned int tem 4 em windows e linux
    }Conversor;

    Conversor conv;
    conv.inicial = 0xCE87;//Valor random
    printf("%02X %02X %02X %02X\n", conv.leitor[0], conv.leitor[1], conv.leitor[2], conv.leitor[3]);


    return 0;   
}

link

    
26.06.2015 / 02:20
0

Basically anything like this

unsigned int valor = 1042;
unsigned char vetor[38]; // escolher limite apropriado
int len = snprintf(vetor, sizeof vetor, "%u", valor);
// vetor 'e a string "1042", ou seja
// vetor[0] == '1'; vetor[1] = '0'; vetor[2] = '4'; vetor[3] = '2'; vetor[4] = '
for (int k = 0; k < len; k++) vetor[k] -= '0'; // vetor ja nao 'e uma string!
// vetor[0] == 1; vetor[1] = 0; vetor[2] = 4; vetor[3] = 2;
';

If you want to convert to values instead of characters, decrement '0' to each character

unsigned int valor = 1042;
unsigned char vetor[38]; // escolher limite apropriado
int len = snprintf(vetor, sizeof vetor, "%u", valor);
// vetor 'e a string "1042", ou seja
// vetor[0] == '1'; vetor[1] = '0'; vetor[2] = '4'; vetor[3] = '2'; vetor[4] = '
for (int k = 0; k < len; k++) vetor[k] -= '0'; // vetor ja nao 'e uma string!
// vetor[0] == 1; vetor[1] = 0; vetor[2] = 4; vetor[3] = 2;
';
    
24.06.2015 / 19:33