开发者

Hexadecimals in python

I don't know python and I'm porting a library to C#, I've encountered the following lines of code that is used in some I/O operation but I'm not sure what it is, my guess is that it's a hexadecimal but I don't know why it's inside a string, neither what the backslashes do?

    sep1 = '\x04H\xfe\x13' # record separator
    sep2 = '\x00\xdd\x01\x0fT\x0开发者_如何转开发2\x00\x00\x01'  # record separator


They're escape sequences. In Python, \xNN within a (non-raw) string is treated as the character 0xNN.


The backslashes are escape characters. They allow you to insert special characters (IE a quotation mark) inside a string. \xNN is hexadecimal, like you say.

It looks like they're using a string in place of an array to me. I'm not really sure why someone would do this... but oh well

I'm not familiar with C#, but in C, sep1 is similar to char[] {0x04H, 0xfe, 0x13} (with an additional 0 at the end if it's a null terminated string)


The same escape sequence works in most languages. You'll just have to use the proper string quotes, in C# that's the double quote (").


As others have stated it's escaped characters that can't really be represented as US ASCII characters. Why do you do this then?

The IO device needs a sequence of bytes with these special hexadecimal values for some reason.

Some languages does not support a native type for bytes, and then we have a problem. How can we write and send out a sequence of bytes when we can't have them in a variable?

The language C uses characters and strings of characters to store those bytes instead. So what you have is not really a string. Think of it as a sequence of bytes instead (stored in a string).

The "string" can be used as normal, i.e it can be sent to the I/O device just as any other character can be sent, and usually withe the same kind of functions (Write, Put, Print,...)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜