【发布时间】:2016-11-03 11:58:45
【问题描述】:
我正在尝试将整数转换为字节(又名无符号字符)数组,以通过 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";
【问题讨论】:
-
你确定你机器的字节顺序了吗?
-
很难判断代码中缺少的 cmets 何时不显示结果数组应该存在的位置 - 要么提供其地址/对它的引用作为参数,要么动态分配它。考虑更改函数的名称 - 至少更改为
…Bytes…()。 -
在这种情况下,这应该没有问题,因为我在同一台机器上来回移动相同的字节。但是一旦我通过 TCP 流传输数据,这可能会出现问题。
标签: c++ arrays integer byte endianness