python - 同样都是表示十六进制,'0x2d'和'\x2d'有什么区别
迷茫
迷茫 2017-04-17 13:04:10
0
4
927

如题,这两种表示方法有什么区别。都在什么情况下使用

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(4)
洪涛

'0x20' is a multi-character character constant and its corresponding value is 0x30783230

(注: '0' 'x' '2' 的 ascii 码分别是 0x30 0x78 0x32)

'x20' is a char and its value is 0x20

(注: '\x[0-9a-fA-F]{1,2}' 用16进制表示一个char 比如 '\xFF'
     '\[0-7]{1,3}' 用8进制表示一个char 比如 '0' )

$ cat 1.c

#include <stdio.h>

int main() {
  int a = '0x20';
  int b = '\x20';
  printf("a = 0x%x\n", a);
  printf("b = 0x%x\n", b);
  return 0;
}

$ gcc -Wall 1.c

1.c:4:11: warning: multi-character character constant [-Wmultichar]
   int a = '0x20';
           ^

$ ./a.out

a = 0x30783230
b = 0x20
洪涛

You can think that '0x2d' is a syntax error and 'x2d' is the correct way of writing.

Specifically, '0x2d' is not a char, but an int. Its value is 0x30783264 or 0x64327830. Which one depends on the implementation.

The C standard says this:

3.1.3.4 Character Constants Semantics
An integer charcter constant has type int [note that it has type char in C++]...The value of an integer character constant containing more than one character...is implementation-defined.

Note that it mentions that the type of this thing in C++ is char. As far as I know, at least VC supports writing like this: 'xe5xadx97', which is a UTF-8 encoded "word".

黄舟

'x2d' is mainly used to represent the encoding of a single-byte character that cannot be displayed directly

'0x2d' should be regarded as a standard hexadecimal string, which can be converted to an int type value through int('0x2d', 16)

阿神

'0x2d' is a string containing 4 characters, 'x2d' represents the character '-' (its ASCII value is 0x2d=45).

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template