C++:将 unsigned long long int 转换为向量反之亦然
谁能告诉我如何将 unsigned long long int 转换为向量,反之亦然。
为了从 unsigned long long int 转换为向量,我尝试了以下操作:
unsigned long long int x;
vector<char> buf(sizeof(x));
memcpy( &buf[0], &x, sizeof( x ) );
当我测试 x = 1234567890 时,它失败了。但是当我尝试使用较小的 x 值(例如 1-100)时,它起作用了......
为了将向量转换为 unsigned long long int,我使用了:
unsigned long long int = (unsigned long long int)buf[0];
谁能告诉我该怎么做。
Can anyone tell me how to convert unsigned long long int into vector and vice versa.
For converting from unsigned long long int to vector, I tried the following:
unsigned long long int x;
vector<char> buf(sizeof(x));
memcpy( &buf[0], &x, sizeof( x ) );
When I tested for x = 1234567890, it failed. But when I tried it for smaller values of x (say 1-100), it works...
For converting vector to unsigned long long int, I used:
unsigned long long int = (unsigned long long int)buf[0];
Can anyone tell me how to do it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请记住,复制字节不能跨平台移植。您的 memcpy 看起来不错,那么为什么不在返回时重新创建它呢?您编写的内容只是获取向量的第一个字节并将其转换为
unsigned long long
这解释了为什么它适用于小数字。尝试以下方法从向量中获取值:
Just remember that copying bytes around won't be cross-platform portable. Your memcpy looks fine, so why not re-create that on the way back out? What you've written simply takes the first byte of the vector and converts it to an
unsigned long long
which explains why it works for small numbers.Try this instead to get the value back out of the vector:
您可以使用
std::vector::assign
来执行复制,而不是直接memcpy
到向量中。输出:
Instead of
memcpy
ing directly into the vector you can usestd::vector::assign
to perform the copying.Output:
你必须改变你的最后一行:
编辑我在胡说八道,那行本来就很好,但是你的转换回来了很糟糕 - 你转换了值,而不是指针:
You have to change your last line:
Edit I was talking nonsense, that line is fine the way it is, but your conversion back is bad - you convert the value, instead of the pointer: