# How to search for ascii char sequence in binary file

**URL:** <https://www.ruby-forum.com/t/how-to-search-for-ascii-char-sequence-in-binary-file/118058>\
**Category:** Ruby\
**Created:** [October 23, 2007, 4:58pm UTC](https://www.ruby-forum.com/t/how-to-search-for-ascii-char-sequence-in-binary-file/118058 "2007-10-23T16:58:31Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![eclubb](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/ecc23a/32.png) [@eclubb](https://www.ruby-forum.com/u/eclubb)\
**Post date:** [October 23, 2007, 4:58pm UTC](https://www.ruby-forum.com/t/how-to-search-for-ascii-char-sequence-in-binary-file/118058/1 "2007-10-23T16:58:31Z")

</div>

So I’m trying to convert e.g. ‘RIFF’ to e.g. ‘52494646’. What’s the  
best way to do that? I don’t know what the former string will be, be I  
know it will be exactly four characters.

I’m searching a binary file for the latter string, but I’m given the  
former as the search term. I’m thinking something like this for the  
search:

puts File.read(‘file.wav’).index(‘52494646’)

So… best way to do the conversion, and best way to do the search.  
Ideas?

Earle

---

<div class="post-metadata">

**Author:** ![eclubb](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/ecc23a/32.png) [@eclubb](https://www.ruby-forum.com/u/eclubb)\
**Post date:** [October 23, 2007, 5:22pm UTC](https://www.ruby-forum.com/t/how-to-search-for-ascii-char-sequence-in-binary-file/118058/2 "2007-10-23T17:22:02Z")

</div>

> So… best way to do the conversion, and best way to do the search.  
> Ideas?
> 
> Earle

Here’s a way to do the conversion. No ideas on the search.

class String  
def to\_hex\_string  
r = ‘’  
self.each\_byte{|c| r \<\< c.to\_s(16)}  
r  
end  
end

# unit test

require ‘test/unit’

class TestString \< Test::Unit::TestCase

def test\_convert  
assert\_equal( ‘52494646’, ‘RIFF’.to\_hex\_string)  
end

end

Regards,

Gordon
