Converting vector<char> that contains cbor data to const char *

Viewed 96

I have a uint8_t vector which contains cbor bytes and I have to cast or copy the bytes to a const char * to use in a POSIX message queue. I've tried the following approaches

vector<uint8_t> cbor_data{/*has some data*/};
const char *data = (const char *)(cbor_data.data());

and

vector<uint8_t> cbor_data{/*has some data*/};
char* data = new char[cbor_data.size() + 1];
memcpy(data, cbor_data.data(), cbor_data.size());
data[cbor_data.size()] = '\0';

But only a part of the data gets cast or copied. Both methods seem to fail. I have a few bytes whose value is 0. For example this is what I have in the vector:

a1,69,72,65,6d,69,6e,64,65,72,73,88,a5,66,63,6f,6e,66,69,67,a5,67,65,6e,61,62,6c,65,64,f4,72,72,65,6d,69,
6e,64,65,72,45,78,70,69,72,79,54,79,70,65,72,73,79,73,74,65,6d,43,61,6c,65,6e,64,61,72,54,69,6d,65,6c,72,
65,6d,69,6e,64,65,72,54,69,6d,65,00,66,76,69,65,77,65,64,f4,6b,77,72,69,74,65,41,63,63,65,73,73,66,72,65,
6d,6f,74,65,62,69,64,00,69,70,75,62,6c,69,73,68,65,72,a2,6c,64,6f,4e,6f,74,50,65,72,73,69,73,74,f5,6d,70

and this is what I am left with when I print data:

a1,69,72,65,6d,69,6e,64,65,72,73,88,a5,66,63,6f,6e,66,69,67,a5,67,65,6e,61,62,6c,65,64,f4,72,72,65,6d,69,
6e,64,65,72,45,78,70,69,72,79,54,79,70,65,72,73,79,73,74,65,6d,43,61,6c,65,6e,64,61,72,54,69,6d,65,6c,72,
65,6d,69,6e,64,65,72,54,69,6d,65,00

Everything after the 00 seems to be lost. Its not just while printing data. strlen(data) and cbor_data.size() dont match. Is there another way to go about this? Or a better way to pass a vector of char/uint8_t to a posix message queue?

2 Answers

Question:

a better way to pass a vector of char/uint8_t to a posix message queue?

The actual question is in your comment,

I can pass the actual size but on the receiving end the buffer has size that is way greater than the actual message length.

Since it's a raw pointer, and mq_receive has to be given a larger size than msg's actual size.

The way to know actual data length on recv size is to define your own protocol of message.

Eg: First 4 bytes for data length, second 4 bytes stating source process tag, and rest of data is cbor data.

A simple chart:

================================================================
| Data Legnth | Process ID or insert what you want | cbor data |
================================================================

As already stated, a char 00 terminates C style strings.

If the receiver expects CBOR, binary data, it should handle a 00 char.

00 = 3 bits 000 signifying an unsigned int + 5 bits payload 0-23 or a byte length indicator, in this case unsigned int payload 0. The unsigned int 0 could also be represent longer, but it always ends with at least one 0 byte.

You might try a "negative" integer with 0: 3 bits 001 + payload 00000.

So attempt substituting 00 with 0x40. No experience with CBOR, so not sure.

Related