這是一個字符編碼的問題會工作得很好。閱讀從JPEG前4個字節返回一個ASCII編碼的字符串:在另一方面
head = File.read("some.jpg", 4)
# => "\xFF\xD8\xFF\xE1"
head.encodig
# => #<Encoding:ASCII-8BIT>
字符串是UTF-8編碼:
jpg_prefix = "\xff\xd8\xff"
# => "\xFF\xD8\xFF"
jpg_prefix.encoding
# => #<Encoding:UTF-8>
比較UTF-8和ASCII字符串不爲工作預計:
head[0,3] == jpg_prefix
# => false
你必須明確地設定String#force_encoding
編碼:
jpg_prefix = "\xff\xd8\xff".force_encoding(Encoding::ASCII_8BIT)
# => "\xFF\xD8\xFF"
jpg_prefix.encoding
# => #<Encoding:ASCII-8BIT>
head[0,3] == jpg_prefix
# => true
與Integer#chr
(由馬里奧Visic建議)創建級聯ASCII字符也可以工作:
jpg_prefix = 0xff.chr + 0xd8.chr + 0xff.chr
# => "\xFF\xD8\xFF"
jpg_prefix.encoding
# => #<Encoding:ASCII-8BIT>
或使用Array#pack
:
jpg_prefix = ["FFD8FF"].pack("H*")
# => "\xFF\xD8\xFF"
jpg_prefix.encoding
# => #<Encoding:ASCII-8BIT>
你的數據是怎樣的? –
@Anand我使用data [0,3]來獲取我在 – Kyle