Comparing bytes in Ruby
binary, image-processing, ruby
Solution
This is an encoding issue. You are comparing a string with binary encoding (your JPEG blob) with a UTF-8 encoded string (`"\xFF"`):
foo = "\xFF".force_encoding("BINARY") # like your blob
bar = "\xFF"
p foo # => "\xFF"
p bar # => "\xFF"
p foo == bar # => false
There are several ways to create a binary encoded string:
str = "\xFF\xD8".b # => "\xFF\xD8" (Ruby 2.x)
str.encoding # => #<Encoding:ASCII-8BIT>
str = "\xFF\xD8".force_encoding("BINARY") # => "\xFF\xD8"
str.encoding # => #<Encoding:ASCII-8BIT>
str = 0xFF.chr + 0xD8.chr # => "\xFF\xD8"
str.encoding # => #<Encoding:ASCII-8BIT>
str = ["FFD8"].pack("H*") # => "\xFF\xD8"
str.encoding # => #<Encoding:ASCII-8BIT>
All of the above can be compared with your blob.
Problem
I have a binary blob header of either a JPG or MP4 file. I am trying to differentiate between the two. When the file is a JPG, the first two bytes are `\xFF\xD8`. However, when I make the comparison `blob[0] == "\xFF"`, it fails. Even when I know that `blob[0]` IS in fact `\xFF` What is the best way to do this?