int to byte array
#include <vector>
using namespace std;
vector<unsigned char> intToBytes(int paramInt) { vector<unsigned char> arrayOfByte(4); for (int i = 0; i < 4; i++) arrayOfByte[3 - i] = (paramInt >> (i * 8)); return arrayOfByte; }
byte array to int
#include <iostream>
#include <cstring>
int main() { unsigned char bytes[4] = { 0xdd, 0xcc, 0xbb, 0xaa }; int value; std::memcpy(&value, bytes, sizeof(int)); std::cout << std::hex << value << '\n'; }
实例:
int intSize = 4; vector<unsigned char> arrayOfByte(4); for (int i = 0; i < 4; i++) arrayOfByte[3 - i] = (intSize >> (i * 8)); byte byteSize[4] ={ arrayOfByte[3],arrayOfByte[2],arrayOfByte[1],arrayOfByte[0]}; int size; std::memcpy(&size, byteSize, sizeof(int));