I want to define a constant string containing non printable characters in C. For e.g - Let say I have a string
char str1[] ={0x01, 0x05, 0x0A, 0x15};
Now I want to define it like this
char *str2 = "<??>"
What should I write in place of <??>
do define an string equivalent to str1
?
Techopedia Explains Non-Printable CharactersWhite spaces (considered an invisible graphic) Carriage returns. Tabs. Line breaks.
String Literals. A String Literal, also known as a string constant or constant string, is a string of characters enclosed in double quotes, such as "To err is human - To really foul things up requires a computer." String literals are stored in C as an array of chars, terminted by a null byte.
The ASCII characters can be divided into several groups. Control Characters (0–31 & 127): Control characters are not printable characters. They are used to send commands to the PC or the printer and are based on telex technology. With these characters, you can set line breaks or tabs.
You can use "\x01\x05\x0a\x15"
If you want to use both a string literal and avoid having an extra terminator (NUL character) added, do it like this:
static const char str[4] = "\x1\x5\xa\x15";
When the string literal's length exactly matches the declared length of the character array, the compiler will not add the terminating NUL character.
The following test program:
#include <stdio.h>
int main(void)
{
size_t i;
static const char str[4] = "\x1\x5\xa\x15";
printf("str is %zu bytes:\n", sizeof str);
for(i = 0; i < sizeof str; ++i)
printf("%zu: %02x\n", i, (unsigned int) str[i]);
return 0;
}
Prints this:
str is 4 bytes:
0: 01
1: 05
2: 0a
3: 15
I don't understand why you would prefer using this method rather than the much more readable and maintainable original one with the hex numbers separated by commas, but perhaps your real string contains normal printable characters too, or something.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With