I am trying to convert integers into byte (aka unsigned char) arrays to send the array over a TCP Stream in C++ and vice versa.
I have tried many solutions on stackoverflow and own ideas but nothing really seems to work for me.
My last solution looks like this:
#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);
}
Everytime I execute this code I get the result "4202308" no matter what I set as "int number".
Any help would be appreciated.
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;
}
Excerpt from 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