开发者

Defining a constant string containing non printable character in C

开发者 https://www.devze.com 2023-01-26 17:02 出处:网络
I want to define a constant string containing non printable characters in C. For e.g - Let say I have a string

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 开发者_如何学Pythonequivalent to str1?


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.


You could use :

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

See escape sequences on MSDN (couldn't find a more neutral link).

0

精彩评论

暂无评论...
验证码 换一张
取 消