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

丶灬走出姿态 提交于 2019-12-08 08:39:16

问题


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.


回答1:


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).




回答2:


You can use a union.

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



回答3:


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 ];
            }
    }



回答4:


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.



来源:https://stackoverflow.com/questions/9345555/how-to-cast-an-int-array-to-a-byte-array-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!