简体   繁体   English

将整数插入char数组

[英]Insert integer into char-array

I have the following char array: 我有以下字符数组:

char* a = new char[6]{0};

Which in binary is: 在二进制中是:

00000000 00000000 00000000 00000000 00000000 00000000

I also have an integer: 我也有一个整数:

int i = 123984343;

Which in binary is: 在二进制中是:

00000111 01100011 11011001 11010111

I would like to insert this 4-byte-integer i into the char array a from position [1] to position [4] so that the original array a becomes: 我想将此4字节整数i从位置[1]插入到位置[4]的char数组a ,以便原始数组a变为:

00000000 00000111 01100011 11011001 11010111 00000000

What is the quickest and easiest method to do that? 最快和最简单的方法是什么?

Use the copy algorithm and a cast to char to access the underlying byte sequence: 使用copy算法和强制转换为char来访问基础字节序列:

#include <algorithm>
#include <cstdint>

std::uint32_t n = 123984343;
char * a = new char[6]{};

{
    const char * p = reinterpret_cast<const char *>(&n);
    std::copy(p, p + sizeof n, a + 1);
}

In this case I am assuming that you are guaranteeing me that the bytes of the integer are in fact what you claim. 在这种情况下,我假设您向我保证,整数字节实际上就是您所声明的内容。 This is platform-dependent, and integers may in general be laid out differently. 这是依赖于平台的,并且整数通常可以不同地布局。 Perhaps an algebraic operation would be more appropriate. 也许代数运算会更合适。 You still need to consider the number of bits in a char ; 您仍然需要考虑char的位数; the following code works if uint8_t is supported: 如果支持uint8_t则以下代码有效:

std::uint8_t * p = reinterpret_cast<std::uint8_t *>(a);
p[1] = n / 0x1000000;
p[2] = n / 0x0010000;
p[3] = n / 0x0000100;
p[4] = n / 0x0000001;

You can solve the problem as asked with 您可以按照要求解决问题

    memcpy( &a[1], &i, sizeof(i) );

but I bet dollars to doughnuts that this is not the best way of solving your problem. 但我赌美元给甜甜圈,这不是解决您问题的最佳方法。

    for (size_t ix = 0; ix < 4; ix++)
    {
        a[1+ix] = (static_cast<unsigned int>(i) >> (8*ix)) & 0xff;
    }

Is a safe way of serializing an int which fits into four bytes into a character array. 将序列号(适合四个字节)的int序列化为字符数组的一种安全方法。 Neither this end, nor the other end, have to make non-portable assumptions. 此端或另一端都不必做出不可移植的假设。

I'm not convinced that even this is the best way of solving your actual problem (but it hard to tell without more information). 我不认为这甚至是解决实际问题的最佳方法(但是如果没有更多信息,很难说清)。

If int is of 4 bytes, then copy the int to address of 2nd position in the char array. 如果int为4个字节,则将int复制到char数组中第二个位置的地址。

int i = 123984343;  
char* a = new char[6]{0};   
memcpy(a+1, &i, sizeof(i));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM