C++ 将内置类型转换为矢量<;char>;
我的TcpClient类在其SendData方法中接受向量,如下所示:C++ 将内置类型转换为矢量<;char>;,c++,C++,我的TcpClient类在其SendData方法中接受向量,如下所示: void CTcpClient::SendData(const vector<char>& dataToTransmit) vector<char> temp( sizeof( yourVariable ) ); memcpy( &temp[0], &yourVariable, sizeof( yourVariable ) ); void CTcpClient::SendD
void CTcpClient::SendData(const vector<char>& dataToTransmit)
vector<char> temp( sizeof( yourVariable ) );
memcpy( &temp[0], &yourVariable, sizeof( yourVariable ) );
void CTcpClient::SendData(const vector和dataToTransmit)
因此,为了使用该函数,我必须将任何内置类型(int、long、short、long-long)转换为向量
我尝试了几种使用流的解决方案,但最终总是得到我想要转换的数字的ASCII表示(我还尝试使用二进制标志,但没有成功)。但我需要这些数字的二进制值
例如:
int num = 0x01234567
vector<char> whatIWant = {0x01, 0x23, 0x45, 0x67}
int num=0x01234567
向量whatIWant={0x01、0x23、0x45、0x67}
你有什么建议
谢谢你的帮助 首先,不要发送
int
s和其他大于char
的类型,这样会忽略endianness,收件人可能无法正确解释数据
其次,您可以重载该方法以接受内置类型,并使用类似htons()
inside的函数以独立于机器的方式将数据转换为网络层顺序
如果仍要使用向量
,请使用类似以下内容:
void CTcpClient::SendData(const vector<char>& dataToTransmit)
vector<char> temp( sizeof( yourVariable ) );
memcpy( &temp[0], &yourVariable, sizeof( yourVariable ) );
vector temp(sizeof(变量));
memcpy(&temp[0],&yourVariable,sizeof(yourVariable));
忽略结尾:
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) );
模板
char*begin_binary(const T&obj){return reinterpret_cast(&obj);}
模板
char*end_binary(const T&obj){return begin_binary(obj)+sizeof(obj);}
int num=0x01234567;
向量whatIWant(开始二进制(num),结束二进制(num));
但是,我将使用无符号字符
作为字节类型
我觉得有必要补充一点,即像往常一样,使用reinterpret\u cast
使此实现的结果具体化。我认为人们可以想象(尽管几乎没有)一个实现,其中char
比T
使用的某种类型具有更严格的对齐,并且重新解释cast
会触发硬件异常。然而,我认为这种可能性是相当学术的。
此外,这两个函数可能会受益于限制
T
的编译时断言。通常,指针、struct
(包含指针)和非POD类型不应与此一起使用 为什么不重载SendData()
以接受内置类型?您还可以重载SendData()
以接受“first”和“last”迭代器,这样用户就可以使用其他容器。@在硅片中:我知道我可以重载SendData()以接受内置类型。但我想知道的是如何实际转换它们。我在示例中介绍了处理endian问题的函数。在内部,所有多字节类型都正确地转换为网络字节顺序。@nabulke:好的,那就这样吧。这是中性的。当然它会起作用,这是“迭代器方式”,它只写了一次向量元素(在我的回答中,它们被写了两次),但这让我再次怀疑迭代器是否有什么做不到的。@sharptooth:这不是为了迭代器,而是为了std::vector
。唯一接受现有数据的std::vector
ctor需要迭代器,为了使用迭代器,您需要传递迭代器。是的,我理解这背后的意图。将数据写入缓冲区而不首先将缓冲区置零显然更好。