开发者

Assigning multiple integers to a character array in binary

I have three integers (4 bytes of memory for each integer) and I want to assign each of their binary values to a character array with 12 elements. So, if each integer had a value of let's say 2, then I want the character array to have these values:

2 0 0 0 2 0 0 0 2 0 0 0
开发者_StackOverflow社区

I have tried:

memcpy(cTemp, &integer1 + &integer2 + &integer3, 12);

but I receive an "invalid operands" compiler error.

I have also found the function strcat referenced here: http://www.cplusplus.com/reference/clibrary/cstring/

However it is mentioned as: "The terminating null character in destination is overwritten by the first character of source" which I obviously don't want since most of the times integers will have a null character at the end unless the value is really large. Does anybody know of a better working method? Any help is appreciated.


It is probably simpler (if you are on a x86 at least :P) to just cast the pointer and assign directly. i.e.

int* p = (int*) cTemp; 
p[0] = a;
p[1] = b;
p[2] = c;


You can also do a union hack:

union translate {
    char c[sizeof(int) * 3];
    int i[3];
};

translate t;
t.i[0] = 2;
t.i[1] = 2;
t.i[2] = 2;

// access t.c[x] to get the chars

... and read the chars...


If you want to see how a variable is represented as a sequence of bytes, you can do the following.

int i[3] = {2, 2, 2};
char cTemp[sizeof i];
memcpy(cTemp, &i, sizeof i);

Note however that the representation will be different on different platforms. What are you trying to solve?

Edit:

I'm just writing a program to edit [a file], and the file happens to store integers in binary.

Why didn't you say so in the first place? If you know the program will only run on platforms where int has the correct memory-layout, you can simply store the integer.

fout.write((char const *)&i, sizeof i);

However, if you want to be portable, you need to properly serialize it.

void store_uint32_le(char * dest, unsigned long value)
{
    for (int i = 0; i < 4; ++i)
    {
        *dest++ = value & 0xff;
        value >>= 8;
    }
    assert(value == 0);
}

int main()
{
    char serialized[12];
    store_uint32_le(serialized, 2);
    store_uint32_le(serialized + 4, 2);
    store_uint32_le(serialized + 8, 2);

    std::ofstream fout("myfile.bin", std::ios::binary);
    fout.write(serialized, sizeof serialized);
}


I think this should work:

int i,j,k;

char a[12];

*((int*)a) = i;
*(((int*)a)+1) = j;
*(((int*)a)+2) = k;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜