Why is my Char* empty after filling with integers?

0

I would like to save several integers in a char pointer and then send this pointer with sendto (winsock2). Unfortunately my char pointer always only contains "\n". Right at the creation and also after filling. What have I done wrong?

uint32_t id = getID();
uint8_t inputType = getInputType(), inputValue = getInputValue();
char* inputBuffer = new char[6];
inputBuffer[0] = (id >> 24) & 0x000000ff;
inputBuffer[1] = (id >> 16) & 0x000000ff;
inputBuffer[2] = (id >> 8) & 0x000000ff;
inputBuffer[3] = (id >> 0) & 0x000000ff;
inputBuffer[4] = (inputType >> 0) & 0x000000ff;
inputBuffer[5] = (inputValue >> 0) & 0x000000ff;

// Send to Server
sendto(socket, inputBuffer, 6, 0, (SOCKADDR*)&srvAddr_In, sizeof(SOCKADDR));

delete[] inputBuffer;

id, inputType and inputValue always contain a valid number. For example I tried id = 10, inputType = 4 and inputValue = 6

c++
networking
char
asked on Stack Overflow Jun 16, 2020 by Timer

2 Answers

2

You char pointer does not contain '\n', at least not in the first position anyway. Rather it contains NUL as the first element, so it will appear blank when displayed as a C-style string.

That's because the least significant 8 bits, obtained with & 0xff, of 10 right-shifted 24 times is zero.

There are data in the char buffer. Note in particular that inputBuffer[3] has the value 10. It's just that you can't see it with your favourite string viewer!

Finally, consider using unsigned char rather than char, as the signedness of char is platform-dependent. (And so is the complementing scheme of char if signed prior to C++14).

answered on Stack Overflow Jun 16, 2020 by Bathsheba • edited Jun 16, 2020 by Bathsheba
0

Let's take it step by step to see what's wrong:

Assuming,

uint32_t id = 100

Bit representation of id will be:

00000000 00000000 00000000 01100100

Step 1.

Statement: inputBuffer[0] = (id >> 24) & 0x000000ff;
Acutally you can just simplify this to: (id >> 24)

Result: inputBuffer[0] = 00000000

Step 2.

Statement: inputBuffer[0] = (id >> 16) & 0x000000ff;

Result: inputBuffer[1] = 00000000

Step 3.

Statement: inputBuffer[0] = (id >> 8) & 0x000000ff;

Result: inputBuffer[2] = 00000000

Step 4.

Statement: inputBuffer[0] = (id >> 0) & 0x000000ff;

Result: inputBuffer[3] = 01100100 // 100

If you try to print inputBuffer at this stage, it will not print anything since the first position contains \0. This is perfectly fine. You just need to be careful on the receiving end of the message.

Recieving end:

uint32_t id = (uint32_t)data[0] << 24)  |
              ((uint32_t)data[1] << 16) |
              ((uint32_t)data[2] << 8)  |
              ((uint32_t)data[3]);
//id == 100
answered on Stack Overflow Jun 16, 2020 by Waqar

User contributions licensed under CC BY-SA 3.0