将内置类型转换为向量< char> [英] Convert built in types to vector<char>

查看:98
本文介绍了将内置类型转换为向量< char>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的TcpClient类在其SendData方法中接受向量< char> ,如下所示:

My TcpClient class accepts vector<char> in its SendData method like this:

void CTcpClient::SendData(const vector<char>& dataToTransmit)

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

Therefore, in order to use the function, I have to convert any built in type (int, long, short, long long) to a vector<char>.

我尝试了几个使用流的解决方案,但总是最终以一个ASCII表示的数字,我想转换(我也试图使用二进制标志没有成功)。但我需要数字的二进制值。

I tried several solutions using streams but always end up with an ASCII representation of the number I want to convert (I also tried to use binary flags without success). But I need the binary values of the numbers.

例如:

int num = 0x01234567
vector<char> whatIWant = {0x01, 0x23, 0x45, 0x67}

您会建议什么解决方案?

What solution would you suggest?

感谢任何帮助!

推荐答案

忽略endianess:

Ignoring 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) );


$ b字节类型。

However, I would use unsigned char as a byte type.

我觉得需要添加到这里,一如既往,使用 reinterpret_cast 实现特定。我想可以想象(虽然勉强)一个实现 char 比用于 T 的类型更严格的对齐 reinterpret_cast 会触发硬件异常。但是,我认为这种可能性相当学术性。

I feel the need to add to this that, as always, the use of reinterpret_cast makes the result of this implementation-specific. I think one could imagine (though barely) an implementation where char has stricter alignment than some type used for T and that reinterpret_cast would trigger a hardware exception. However, I consider this possibility rather academic.

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

Further, the two functions would probably benefit from a compile-time assertion restricting T. Commonly, pointers, struct's containing pointers, and non-POD types shouldn't be used with this.

这篇关于将内置类型转换为向量&lt; char&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆