What's the easiest way to prevent null chars from terminating my string?

364 views Asked by At

I'm currently working on some C code to forward CAN messages via bluetooth and vice versa (µC stuff). The problem is that my paired bluetooth device uses '00' as a command and my bluetooth library is using a char[] to buffer the string when receiving from BT. This inevitably terminates the string, because it interprets the command as a NULL character. Also, any empty data byte in a CAN frame would cause the same problem.

I was able to solve the problem when going from CAN to BT by storing the CAN message in a byte array and sending a series of bytes followed by a CR to the BT module, but the other way round isn't that easy, as the BT library is using all sorts of string based commands.

Is there an easy way to prevent the NULL to cause an unwanted termination or do I have to rewrite the whole library to a suitable data type, and which one would work best in this case? Any ideas appreciated!

1

There are 1 answers

3
Wouter Verhelst On BEST ANSWER

There is no "string" type in C; what you call a string in C really is just a char *, which is just a series of bytes, too. Whenever you pass such a series of bytes to a string handling function (whether part of the standard C library or not), those functions will consider any embedded NULL as a string termination, and end processing there. That doesn't mean your binary data ends at that location, however.

Your problem isn't that your library gets you strings, it's that you're confusing binary data with strings. You're not dealing with strings, you're dealing with binary data. If it helps, you can cast the char * variables to void * variables; this isn't strictly necessary, but it may help you remember that it's binary data. Then, use a packed struct (if the data has fixed offsets) or write a custom parser function (if not) to deal with the data going in or out of your CAN bus.