1

I have am array of uint8:

uInt8 data1[88];

I want to convert it to the byte array (char*). I tried

char * temp = reinterpret_cast<char*>(data1);

which work for double[], but there is no data in output and strlen(temp) is 0. I print all data1's elements but it was blank and when I convert it's elements to the string (using the to_string), it will print 0 and 1.

How can I solve the problem?

Soheil Pourbafrani
  • 3,249
  • 3
  • 32
  • 69
  • What is the *contents* of the array? Is it a *null-terminated byte string*? Or just arbitrary byte values? – Some programmer dude Aug 15 '18 at 08:02
  • Your conversion code is correct. Your problem is somewhere else. – john Aug 15 '18 at 08:02
  • [char is allowed to alias](https://stackoverflow.com/a/51228315/1708801) but you still need to initialize your data. – Shafik Yaghmour Aug 15 '18 at 08:05
  • @Someprogrammerdude It should contain just 0 and 1. – Soheil Pourbafrani Aug 15 '18 at 08:07
  • 2
    The *integer* values `0` and `1`, or the *characters* `'0'` and `'1'`? Those two are *very* different. And don't forget that the *null-terminator* in a *null-terminated byte string* is equal to the *integer* value `0`. And that using any string functions (like e.g. `strlen`) on something which *isn't* a null-terminated byte string leads to [*undefined behavior*](https://en.wikipedia.org/wiki/Undefined_behavior). – Some programmer dude Aug 15 '18 at 08:07
  • @Someprogrammerdude Thanks, it's integer values. How can I prevent the undefined behavior? – Soheil Pourbafrani Aug 15 '18 at 08:16
  • What are you going to do with the values in the array? Print them? Then why not use a loop to print them one by one? Or if you need characters, why not create a proper [`std::string`](http://en.cppreference.com/w/cpp/string/basic_string) containing the character equivalents of the values in the array (or possibly create the string and skip the array)? What you should or need to do really depends on your requirements, and what the code is supposed to do. – Some programmer dude Aug 15 '18 at 08:19
  • @Someprogrammerdude my goal is to merge them to other char* and send the result over the network. – Soheil Pourbafrani Aug 15 '18 at 08:20
  • 2
    Are you supposed to send the raw binary integer values `0` and `1`? Or as text? If you need to send the integer values as is, then don't bother with texts or using any text functions, just send the data (`uint8` is most likely an alias of `unsigned char` so it should work fine with a simple cast). If you need to send the data as *text* then use `std::string` and don't bother with the integer values, only characters. – Some programmer dude Aug 15 '18 at 08:22

0 Answers0