Reputation: 73
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
Reputation: 9587
If you want to
int
array as bytes,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
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
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 char
s, 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 char
s, as there were int
s, then you cannot do this without a loop and manual conversion (to a new memory locaton, normally).
Upvotes: 15