C語言二進制拼接 (整數和byte類型的字符串拼接)


#include <iostream>
#include <cstring>
#include <cstdio>

using namespace std;

typedef unsigned char Byte;

Byte * intToBytes(const int& N) {

Byte* byte = new Byte[4];

byte[0] = (N >> 24) & 0xFF;
byte[1] = (N >> 16) & 0xFF;
byte[2] = (N >> 8) & 0xFF;
byte[3] = N & 0xFF;

return byte;
}

// 將一個byte數組、一個整數、一個整數以及一個byte數組組合為一個byte數組,並返回。
Byte * Cat(Byte *a, int b, int c, Byte *d)
{
Byte* res = new Byte[12];
memcpy(res, a, 2);// 2 為數組a的長度
memcpy(res + 2, intToBytes(b), 4);// 2 為int的長度
memcpy(res + 6, intToBytes(c), 4);
memcpy(res + 10, d, 2);// 2 為數組a的長度
return res;
}

int main()
{
Byte a[2]={253,27};
int b=16;
int c=18;
Byte d[2]={222,92};

Byte * res = Cat(a, b, c, d);
cout<<res<<endl;
// for (int i = 0; i < 12; i++)
// printf("%c", res[i]);
return 0;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM