jijuji
jijuji

Reputation: 1

Access and read a char array as an int array

I haven't found any solution among the many many threads about this. My exact problem is:

I have an array of integers such as unsigned int arr[2] = {0xFEBD1213, 0x1213FEBD};

I would like to access those integers char by char, meaning that I need to read : 0x13, 0x12, 0xBD, 0xFE, 0xBD, 0xFE, 0x13, 0x12. I tried many, many things and I did not succeeded yet.

Note : I would also like to do the opposite : having a char array with a size such as size %4 == 0, and reading it as an integer array. E.g : unsigned char arr[8] = {0x13, 0x12, 0xBD, 0xFE, 0xBD, 0xFE, 0x13, 0x12} and read 0xFEBD1213, 0x1213FEBD;

Is there any way of doing such a thing?

Minimal reproducible example:

#include <stdio.h>
#include <stdlib.h>
void main(void){
  unsigned int arr[2] = {0xFEBD1213, 0x1213FEBD};
  unsigned char * ptr;
  ptr = *&arr; // I need a variable. Printing it doesn't matter to me. I am aware that there are easy solutions to print the right values there.
  for(int i = 0; i < 2 * 4; i++){
    printf("%x\n", *ptr);
    ptr = (ptr++);
  }
}

(I am aware that there are many cleaner way to code this, but I don't have the control over the type of the given array)

Upvotes: 0

Views: 174

Answers (3)

MrBens
MrBens

Reputation: 1260

You can use some kind of a parser:

void AccessAsCharArr(void *arr, size_t size);

int main()
{
    unsigned int arr[] = {0xFEBD1213, 0x1213FEBD, 0xFF000366};
    AccessAsCharArr(arr, sizeof(arr));
    return 0;
}

void AccessAsCharArr(void *arr, size_t size)
{
    unsigned char *ptr = arr;

    for (size_t i = 0; i < size; i++)
    {
        printf("%hhx ", *ptr);
        ptr++;  
    }
}

Upvotes: 0

jijuji
jijuji

Reputation: 1

#include <stdio.h>
#include <stdlib.h>
void main(void){
  unsigned int arr[2] = {0xFEBD1213, 0x1213FEBD};
  unsigned char * ptr;
  ptr = &arr;
  for(int i = 0; i < 2 * 4; i++){
    printf("%x\n", *ptr);
    ptr = &*(ptr)+1;

  }

  unsigned char arr_c[8] = {0x13, 0x12, 0xBD, 0xFE, 0xBD, 0xFE, 0x13, 0x12};
  unsigned int * ptr_i;
  ptr_i = &arr_c;
  for(int i = 0; i < 2; i++){
      printf("%x\n", *ptr_i);
      ptr_i = &*(ptr_i)+1;
  }
}

Upvotes: -1

David C. Rankin
David C. Rankin

Reputation: 84561

A simple shift and AND will work:

#include <stdio.h>
#include <limits.h>

int main (void) {

    unsigned int arr[2] = {0xFEBD1213, 0x1213FEBD};

    for (size_t i = 0; i < 2; i++)
        for (size_t j = 0; j< sizeof *arr; j++)
            printf ("0x%hhx\n", arr[i] >> (j * CHAR_BIT) & 0xff);
}

Example Use/Output

$ ./bin/arrbytes
0x13
0x12
0xbd
0xfe
0xbd
0xfe
0x13
0x12

To go from bytes to array just shift the opposite direction and OR.

Upvotes: 2

Related Questions