[英]Changing Double Quotes to Single
I'm working on a project in Ruby. 我正在Ruby中进行项目。 The library I'm using returns a string in double quotes, for example: "\\x00\\x40"
. 我正在使用的库返回带双引号的字符串,例如: "\\x00\\x40"
。 Since the string is in double quotes, any hex that can be converted to an ASCII character is converted. 由于字符串用双引号引起来,因此可以转换为ASCII字符的所有十六进制都会被转换。 Therefore, when I print, I actually see: "\\x00@"
. 因此,当我打印时,我实际上看到: "\\x00@"
。
I figured out that, if I use single quotes, then the string will print in pure hex (without conversion), which is what I want. 我发现,如果我使用单引号,则字符串将以纯十六进制(无需转换)打印,这就是我想要的。 How do I change a double quoted string to single quoted? 如何将双引号字符串更改为单引号?
I do not have any way to change the return type in the library since it is a C extension, and I can't figure out where the value is being returned from. 由于它是C扩展,因此我无法更改库中的返回类型,而且我无法弄清楚从何处返回该值。 Any ideas greatly appreciated. 任何想法表示赞赏。
"\\x00\\x40"
and '\\x00\\x40'
produce totally different strings. "\\x00\\x40"
和'\\x00\\x40'
产生完全不同的字符串。
"\\x00\\x40"
creates a 2 byte string with hex values 0x00
and 0x40
: "\\x00\\x40"
创建一个2字节的字符串,十六进制值为0x00
和0x40
:
"\x00\x40".length
# => 2
"\x00\x40".chars.to_a
# => ["\u0000", "@"]
'\\x00\\x40'
creates a string with 8 characters: '\\x00\\x40'
创建一个包含8个字符的字符串:
'\x00\x40'.length
# => 8
'\x00\x40'.chars.to_a
# => ["\\", "x", "0", "0", "\\", "x", "4", "0"]
This is done by Ruby's parser and you cannot change it once the string is created. 这是由Ruby的解析器完成的,一旦创建了字符串,您将无法更改它。
However, you can convert the string to get its hexadecimal representation. 但是,您可以转换字符串以获取其十六进制表示形式。
String#unpack
decodes the string as a hex string, ie it returns the hex value of each byte as a string: String#unpack
将字符串解码为十六进制字符串,即返回每个字节的十六进制值作为字符串:
hex = "\x00\x40".unpack("H*")[0]
# => "0040"
String#gsub
adds/inserts \\x
every 2 bytes: String#gsub
每2个字节添加/插入\\x
:
hex.gsub(/../) { |s| '\x' + s }
# => "\\x00\\x40"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.