c++ int 与 byte array 互转


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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM