1

I have a unsigned char array like this:

unsigned char myArr[] = {100, 128, 0, 32, 2, 9};

I am using reinterpret_cast to covert it to const char* as I have to pass a const char* to a method. This information is then sent over grpc and the other application (erlang based recieves it and stores it in a erlang Bin). But what I observe is the Erlang application only received <<100, 128>> and nothing after that. What could be causing this? Is it the 0 in the character array that is the problem here? Could someone explain how to handle the 0 in an unsigned char array? I did read quite a few answers but nothing clearly explains my problem.

Vishnu CS
  • 748
  • 1
  • 10
  • 24
Purdgr8
  • 33
  • 1
  • 7

1 Answers1

4

What could be causing this? Is it the 0 in the character array that is the problem here?

Most likely, yes.

Probably one of the functions that the pointer is passed to is specified to accept an argument which points to a null terminated string. Your array happens to incidentally be null terminated by containing null character at index 2 which is where the string terminates. Such function would typically only have well defined behavior in case the array is null terminated, so passing pointer to arbitrary binary that might not contain null character would be quite dangerous.

Could someone explain how to handle the 0 in an unsigned char array?

Don't pass the array into functions that expect null terminated strings. This includes most formatted output functions and most functions in <cstring>. The documentation of the function should mention the pre-conditions.

If such functions are your only option, then you can encode the binary data in a textual format and decode it in the other end. A commonly used textual encoding for binary data is Base64 although it is not necessarily the most optimal.

Vishnu CS
  • 748
  • 1
  • 10
  • 24
eerorika
  • 232,697
  • 12
  • 197
  • 326
  • This function is an auto-generated one after compilation of one .proto file. – Purdgr8 Sep 23 '20 at 11:19
  • @Purdgr8 What is "this function"? – eerorika Sep 23 '20 at 11:20
  • The function to which I have to pass the array. So, I am not sure what options I am left with. As for the encoding that you suggest, it would mean adding some decoding mechanism in the other application. Unfortunately, I am not allowed to change the other side of the code. – Purdgr8 Sep 23 '20 at 11:23