Defining a constant string containing a non-printable character in C

I want to define a constant string containing non-printable characters in C. For example, for example - let's say I have a string

char str1[] ={0x01, 0x05, 0x0A, 0x15}; 

Now I want to define it as follows

 char *str2 = "<??>" 

What should be written instead of <??> define a string equivalent to str1 ?

+7
c
source share
3 answers

You can use "\x01\x05\x0a\x15"

+13
source share

If you want to use a string literal and not add an additional terminator (NUL character), do it like this:

 static const char str[4] = "\x1\x5\xa\x15"; 

When the length of the string string exactly matches the declared length of the character array, the compiler will not add the trailing 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; } 

Will print this:

 str is 4 bytes: 0: 01 1: 05 2: 0a 3: 15 

I don’t understand why you would prefer to use this method rather than a more readable and supported original with hexadecimal numbers separated by commas, but maybe your real string also contains plain print characters or something else.

+3
source share

You can use:

const char *str2 = "\x01\x05\x0A\x15";

See escape sequences on MSDN (could not find a more neutral link).

+2
source share

All Articles