将内置类型转换为vector <char>

nab*_*lke 2 c++

我的TcpClient类vector<char>在其SendData方法中接受如下:

void CTcpClient::SendData(const vector<char>& dataToTransmit)
Run Code Online (Sandbox Code Playgroud)

因此,为了使用该函数,我必须将任何内置类型(int,long,short,long long)转换为a vector<char>.

我尝试了几种使用流的解决方案,但总是最终得到我要转换的数字的ASCII表示(我也尝试使用二进制标志而没有成功).但我需要数字的二进制值.

例如:

int num = 0x01234567
vector<char> whatIWant = {0x01, 0x23, 0x45, 0x67}
Run Code Online (Sandbox Code Playgroud)

你会建议什么解决方案?

谢谢你的帮助!

sbi*_*sbi 5

忽略endianess:

template< typename T >
char* begin_binary(const T& obj) {return reinterpret_cast<char*>(&obj);}
template< typename T >
char* end_binary  (const T& obj) {return begin_binary(obj)+sizeof(obj);}

int num = 0x01234567;
vector<char> whatIWant( begin_binary(num), end_binary(num) );
Run Code Online (Sandbox Code Playgroud)

但是,我会将其unsigned char用作字节类型.

我觉得有必要补充一点,一如既往地使用reinterpret_cast这个特定于实现的结果.我认为可以想象(虽然几乎没有)一种实现,其中char比某些类型使用更严格的对齐T并且reinterpret_cast会触发硬件异常.但是,我认为这种可能性相当学术化.

此外,这两个函数可能会受益于编译时断言限制T.通常,指针,struct包含指针和非POD类型不应与此一起使用.