我正在编写一个将数据从uint32_t复制到std :: vector的函数。该程序将在具有不同字节序的不同平台上使用(主要是LE,但有些BE)
当前我正在使用此:
std:vector<uint8_t> Decryption::GenerateIvForBlock(uint32_t blockNumber)
{
std:vector<uint8_t> ivInput(AES128_KEY_BYTE_LENGTH, 0);
// Some code
if (///////)
{
memcpy(&ivInput[0], &blockNumber, sizeof(blockNumber));
}
}
当前,即使在不同平台上的blockNumber相同,行为在不同字节序平台上也有所不同。 不幸的是,我无法轻松地测试Big endian系统,因此我难以解决问题。
答案 0 :(得分:1)
如建议的那样,ntohx()
/ htonx()
函数可以帮助您将16位和32位无符号整数从网络字节顺序转换为主机字节顺序并返回。
已经有一些草稿,其中包括在C ++ ntoh()
标头中包含hton()
和<net>
的模板,但是afaik,没有成功。您可能会在<Winsock2.h>
或<arpa/inet.h>
中找到C函数,因此可以自己创建模板。示例:
#include <cstdint>
#ifdef _WIN32
#include <Winsock2.h>
#else
#include <arpa/inet.h>
#endif
template <class T>
T hton(T host) noexcept = delete;
template <>
uint8_t hton(uint8_t host) noexcept {
return host;
}
template <>
uint16_t hton(uint16_t host) noexcept {
return htons(host);
}
template <>
uint32_t hton(uint32_t host) noexcept {
return htonl(host);
}
template <class T>
T ntoh(T network) noexcept = delete;
template <>
uint8_t ntoh(uint8_t network) noexcept {
return network;
}
template <>
uint16_t ntoh(uint16_t network) noexcept {
return ntohs(network);
}
template <>
uint32_t ntoh(uint32_t network) noexcept {
return ntohl(network);
}
有了这些,就可以使用流运算符为向量创建包装器类模板,以保存和恢复数据。下面是一个非常基本的示例。根据需要添加运算符等。
template <typename T>
class Data {
std::vector<T> m_data;
public:
Data() : m_data{} {}
template< class... Args >
auto emplace_back( Args&&... args ) {
return m_data.emplace_back(std::forward<Args>(args)...);
}
void reserve(typename std::vector<T>::size_type size) {
m_data.reserve(size);
}
bool operator==(const Data& o) {
return m_data == o.m_data;
}
template <typename V>
friend std::ostream& operator<<(std::ostream&, const Data<V>&);
template <typename V>
friend std::istream& operator>>(std::istream&, Data<V>&);
};
template <typename T>
std::ostream& operator<<(std::ostream& os, const Data<T>& d) {
// write the number of entries first
const uint32_t count = hton(static_cast<const uint32_t>(d.m_data.size()));
os.write(reinterpret_cast<const char*>(&count), sizeof(count));
// write all the entries, converted to network byte order
for(auto v : d.m_data) {
v = hton(v);
os.write(reinterpret_cast<const char*>(&v), sizeof(v));
}
return os;
}
template <typename T>
std::istream& operator>>(std::istream& is, Data<T>& d) {
// read the number of entries first
uint32_t count;
is.read(reinterpret_cast<char*>(&count), sizeof(count));
d.m_data.resize(ntoh(count));
// read all the entries and convert to host byte order
for(auto& v : d.m_data) {
is.read(reinterpret_cast<char*>(&v), sizeof(v));
v = ntoh(v);
}
return is;
}
测试:
#include <iostream>
#include <vector>
#include <sstream>
int main() {
Data<unsigned> orig;
Data<unsigned> copy;
std::stringstream ss;
orig.reserve(1024*1024);
for(unsigned i=0; i<1024*1024; ++i) orig.emplace_back(i);
ss << orig; // save to stream
// the data in 'ss' is now in network byte order
ss >> copy; // restore from stream
if(orig==copy) std::cout << "happy\n";
}