我試圖將整數轉換爲byte(aka unsigned char)數組,以通過C++中的TCP Stream發送數組,反之亦然。C++ |將int轉換爲byte [4],反之亦然
我已經嘗試了很多解決方案在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);
}
每次我執行這個代碼,我得到的結果「4202308」不管我設置爲「整型數字」。
任何幫助,將不勝感激。
UPDATE:從
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;
}
摘錄主():
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
在這種情況下,這應該是沒有問題的,因爲我在同一臺機器上來回移動相同的字節。但只要我通過TCP流傳輸數據,這可能會有問題。 – eheller