Apekshith Ramesha
Apekshith Ramesha

Reputation: 73

how to cast an int array to a byte array in C

hey i would like to know how you could cast an Int array in C to an byte array and what would be the declaration method. I would appreciate if it is simpler and no use of pointers. thanks for the comments

ex: int addr[500] to byte[]

Plus I would also want the ending byte array to have the same array name.

Upvotes: 4

Views: 30568

Answers (4)

Simon
Simon

Reputation: 2115

You can use a union.

union {
  int ints[500];
  char bytes[0];
} addr;

Upvotes: 4

Irfy
Irfy

Reputation: 9587

If you want to

  1. reinterpret the memory behind the int array as bytes,
  2. want to avoid pointers syntactically --for whatever reason--, and
  3. making a copy of the int array is acceptable,

then you could create a new char array and copy the int array with memcpy:

int ints[500];
char bytes[500 * 4];
memcpy(bytes, ints, 500 * 4);

This is about the same as the first snippet from my original answer, with the difference that the bytes contain a copy of the ints (i.e. modifying one doesn't influence the other). Usual caveats about int size and avoiding magic constants/refactoring code apply.

Upvotes: 1

vimdude
vimdude

Reputation: 4585

It might be easier to use pointers but without pointers, try the following:

    #include <stdio.h>

    typedef unsigned char byte;

    void main() {
            int addr_size = 500;
            int addr[ addr_size ];
            byte bytes[ addr_size * 4 ];

            int i;
            for( i = 0; i < addr_size; i++ ) {
                    bytes[ i ] = (byte)( addr[ i ] >> 24);
                    bytes[ i + 1 ] = (byte)( addr[ i ] >> 16);
                    bytes[ i + 2 ] = (byte)( addr[ i ] >> 8);
                    bytes[ i + 3 ] = (byte)addr[ i ];
            }
    }

Upvotes: 0

Irfy
Irfy

Reputation: 9587

If you are trying to reinterpret the memory behind the int array as an array of bytes, and only then:

int ints[500];
char *bytes = (char *) ints;

You cannot do this without resorting to pointer casting, as declaring a [] array implies allocation on stack, and cannot be used for reinterpretation of existing memory.

Obviously, you need to know what you are doing. For each int there will be (typically, depending on platform etc.) 4 chars, so your new array would have 500*4 elements. Check out what the output of:

printf("char size: %d, int size: %d", sizeof(char), sizeof(int));

tells you to make sure.

If you are trying to interpret each int as a char, i.e. to get the same number of chars, as there were ints, then you cannot do this without a loop and manual conversion (to a new memory locaton, normally).

Upvotes: 15

Related Questions