0
我有兩個測試用例,其中調用了data_valid?
方法。第一個返回false
,第二個返回true
,爲什麼?爲什麼非ASCII字符不相等?
55: def data_valid? d
56: crc = d[-1]
57: data = d[1..-2]
58: len = d[0]
=> 59: binding.pry
60: (data^len) == crc
61: end
2.0.0 (#<MicroAeth::Message:0x007fbefc3ceae8>):0 > (data^len) == crc
=> false
2.0.0 (#<MicroAeth::Message:0x007fbefc3ceae8>):0 > (data^len)
=> "\xB1"
2.0.0 (#<MicroAeth::Message:0x007fbefc3ceae8>):0 > crc
=> "\xB1"
2.0.0 (#<MicroAeth::Message:0x007fbefc3ceae8>):0 > exit
have a good day!
F
From: /Users/rudolph9/Projects/CombustionEmissionsTesting/micro_aeth.rb @ line 59 MicroAeth::Message#data_valid?:
55: def data_valid? d
56: crc = d[-1]
57: data = d[1..-2]
58: len = d[0]
=> 59: binding.pry
60: (data^len) == crc
61: end
2.0.0 (#<MicroAeth::Message:0x007fbefe83a8c8>):0 > (data^len) == crc
=> true
2.0.0 (#<MicroAeth::Message:0x007fbefe83a8c8>):0 > (data^len)
=> "+"
2.0.0 (#<MicroAeth::Message:0x007fbefe83a8c8>):0 > crc
=> "+"
以下是我在那裏我比較自定義XOR方法^
返回String類的擴展。
class ::String
###
# @return the first charater in the string as an integer
def byte
self.bytes[0]
end
###
# XOR two strings
# @str assumed to be a one byte string or integer
def^str
if str.class == String
str = str.byte
elsif str.class == Fixnum
nil
else
raise "invalid arg: #{str.class} \n Must be String or Fixnum"
end
self.bytes.each do |i|
str = str^i
end
str.chr
end
end
我相信這跟第一次比較非ASCII字符有關。我如何正確設置條件?
什麼是字符串的編碼?調用[#encoding](http://www.ruby-doc.org/core-2.0/String.html#method-i-encoding)對其進行檢查。 –
@XiongChiamiov 2.0.0(#):0> crc.encoding =>#<編碼:UTF-8> 2.0.0(#) :0>(data^len).encoding =>#<編碼:ASCII-8BIT>' –
rudolph9
我在轉換字符串以進行比較時遇到問題:'2.0.0(#) :0>(data^len).encode crc.encoding Encoding :: UndefinedConversionError:從ASCII-8BIT到「UTF-8」的「\ xB1」 from(pry):12:in'encode' 2.0.0(#編碼:: InvalidByteSequenceError:UTF-8上的「\ xB1」 from(pry):13:in'encode''怎麼做我的方法獲得一個共同的編碼? –
rudolph9