我正在尝试将整数转换为字节(也称为无符号字符)数组,以便在C ++中通过TCP流发送该数组,反之亦然。
我已经尝试了stackoverflow上的许多解决方案和自己的想法,但似乎都不太适合我。
我的最后一个解决方案看起来像这样:
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <iostream>
#include "tcpconnector.h"
typedef unsigned char byte;
using namespace std;
/*
char* byteToChar(byte* b, int length) {
char c[length];
for (int i = 0; i < length; i++) {
c[i] = b[i] - 128;
}
return c;
}
byte* charToByte(char* c, int length) {
byte b[length];
for (int i = 0; i < length; i++) {
b[i] = c[i] + 128;
}
return b;
}
*/
byte* intToByte(int n) {
byte byte[4];
byte[0] = n & 0x000000ff;
byte[1] = n & 0x0000ff00 >> 8;
byte[2] = n & 0x00ff0000 >> 16;
byte[3] = n & 0xff000000 >> 24;
return byte;
}
int byteToInt(byte* byte) {
int n = 0;
n = n + (byte[0] & 0x000000ff);
n = n + ((byte[1] & 0x000000ff) << 8);
n = n + ((byte[2] & 0x000000ff) << 16);
n = n + ((byte[3] & 0x000000ff) << 24);
return n;
}
int main(int argc, char** argv)
{
if (argc != 3) {
printf("usage: %s <port> <ip>\n", argv[0]);
exit(1);
}
int number = 42;
byte* line = intToByte(number);
cout << "Number: " << number << "\n";
cout << "ArrayLength: " << sizeof line << "\n";
cout << "Array: " << line << "\n";
cout << "Array to Number: " << byteToInt(line) << "\n";
/*
TCPConnector* connector = new TCPConnector();
TCPStream* stream = connector->connect(argv[2], atoi(argv[1]));
if (stream) {
stream->send(byteToChar(line, 4), 4);
delete stream;
}
*/
exit(0);
}
每次我执行这段代码,无论我将"int number"设置为什么值,都会得到结果"4202308"。
任何帮助将不胜感激。
更新:
void intToByte(int n, byte* result) {
result[0] = n & 0x000000ff;
result[1] = n & 0x0000ff00 >> 8;
result[2] = n & 0x00ff0000 >> 16;
result[3] = n & 0xff000000 >> 24;
}
main()函数中的摘录:
int number = 42;
byte line[4];
intToByte(number, line);
cout << "Number: " << number << "\n";
cout << "ArrayLength: " << sizeof line << "\n";
cout << "Array: " << line << "\n";
cout << "Array to Number: " << byteToInt(line) << "\n";
...Bytes...()
。 - greybeard