简体   繁体   English

将向量值复制到 char*

[英]Copy Vector values to char*

I have three vectors我有三个向量

std::vector<long long unsigned> eightByte_v;
std::vector<unsigned char> oneByteDelta_v;
std::vector<unsigned short> twoByteDelta_v;

and I inserted two values each to vectors我在向量中分别插入了两个值

eightByte_v.pushback(0x111111111111);
eightByte_v.pushback(0x2222222222222222);
oneByteDelta_v.pushback(0x33);
oneByteDelta_v.pushback(0x44);
twoByteDelta_v.pushback(0x5555);
twoByteDelta_v.pushback(0x6666);

I would like to merge all the vectors to char* as follow.我想将所有向量合并到 char* 如下。

    char[0] = 00
    char[1] = 00
    char[2] = 11
    char[3] = 11
    char[4] = 11
    char[5] = 11
    char[6] = 11
    char[7] = 11
    char[8] = 22
    char[9] = 22
    char[10] = 22
    char[11] = 22
    char[12] = 22
    char[13] = 22
    char[14] = 22
    char[15] = 22
    char[16] = 22
    char[17] = 22
    char[18] = 33
    char[19] = 44
    char[20] = 55
    char[21] = 55
    char[22] = 66
    char[23] = 66

from char 0 to 17 is equivalent to eightByte_v从 char 0 到 17 等价于八字节_v
from char 18 to 19 is equivalent to oneByte_v从 char 18 到 19 相当于 oneByte_v
from char 20 to 23 is equivalent to twoByte_v从 char 20 到 23 相当于 twoByte_v

I think I can do it with memcpy , but is there any other way to do it?我想我可以用memcpy做到这一点,但还有其他方法吗?

Thank you in advance!先感谢您!

Alternatives like using a union spring to mind, but it's difficult or impossible to do that in a defined way: you'll invariably encounter structure packing and pointer casting issues.想到使用union等替代方案,但很难或不可能以定义的方式做到这一点:您总是会遇到结构打包和指针转换问题。

Given that the C++ standard guarantees data contiguity in a std::vector (and the data buffer is accessible using the data() function), a memcpy is arguably the best approach.鉴于 C++ 标准保证std::vector中的数据连续性(并且可以使用data()函数访问数据缓冲区), memcpy可以说是最好的方法。

Do bear in mind though that the signed-ness of char is platform dependent.请记住,尽管char的签名依赖于平台。 You might want to be more explicit;你可能想要更明确; consider using an unsigned char .考虑使用unsigned char

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

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