Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining a constant string containing non printable character in C

Tags:

c

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?

like image 709
Ravi Gupta Avatar asked Nov 25 '10 09:11

Ravi Gupta


People also ask

Which character is not a printable character in C?

Techopedia Explains Non-Printable CharactersWhite spaces (considered an invisible graphic) Carriage returns. Tabs. Line breaks.

What is a string constant in C?

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.

Where are non-printing characters defined in the Ascii character sets?

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.


2 Answers

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

like image 116
lijie Avatar answered Sep 27 '22 22:09

lijie


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.

like image 39
unwind Avatar answered Sep 27 '22 20:09

unwind