# How to search for ascii char sequence in binary file

**URL:** <https://rubytalk.org/t/how-to-search-for-ascii-char-sequence-in-binary-file/41607>\
**Category:** ruby-talk\
**Created:** [23 October 2007 14:58 UTC](https://rubytalk.org/t/how-to-search-for-ascii-char-sequence-in-binary-file/41607 "2007-10-23T14:58:30Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Earle\_Clubb](https://avatars.discourse-cdn.com/v4/letter/e/ecb155/32.png) [@Earle\_Clubb](https://rubytalk.org/u/Earle_Clubb)\
**Post date:** [23 October 2007 14:58 UTC](https://rubytalk.org/t/how-to-search-for-ascii-char-sequence-in-binary-file/41607/1 "2007-10-23T14:58:30Z")

</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

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).

---

<div class="post-metadata">

**Author:** ![Gordon\_Thiesfeld](https://avatars.discourse-cdn.com/v4/letter/g/e47774/32.png) [@Gordon\_Thiesfeld](https://rubytalk.org/u/Gordon_Thiesfeld)\
**Post date:** [23 October 2007 15:21 UTC](https://rubytalk.org/t/how-to-search-for-ascii-char-sequence-in-binary-file/41607/2 "2007-10-23T15:21:36Z")

</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  
&nbsp;&nbsp;def to\_hex\_string  
&nbsp;&nbsp;&nbsp;&nbsp;r = ''  
&nbsp;&nbsp;&nbsp;&nbsp;self.each\_byte{|c| r \<\< c.to\_s(16)}  
&nbsp;&nbsp;&nbsp;&nbsp;r  
&nbsp;&nbsp;end  
end

# unit test  
require 'test/unit'

class TestString \< Test::Unit::TestCase

&nbsp;&nbsp;def test\_convert  
&nbsp;&nbsp;&nbsp;&nbsp;assert\_equal( '52494646', 'RIFF'.to\_hex\_string)  
&nbsp;&nbsp;end

end

Regards,

Gordon
