Share via


Binary banner

BoingBoing has a story of a store that sells t-shirts with offensive messages spelled out in binary. I think its a nice way to generate email signature or web-page banner where you can really say offensive stuff and get away with it. I wrote the following code in Ruby which takes any word and spits out the binary ASCII representation.

 ARGV.each do |str|
  def PrintBin(ch)
    mask = 0x80
    while mask != 0
      print (if (ch & mask) == 0 then "0" else "1" end)
      mask >>= 1
    end
  end

  str.each_byte do |ch|
    PrintBin ch
  end
  print "\n"
end

My Ruby is completely rusted so it took me some time to get this done. Later I tried writing the same code in C#. It took me over 3 times the LOC it took me to do it up in Ruby. I'm sure a experinced Ruby programmer can make this even more simpler and concise.

Since this is my official blog, I won't post anything offensive here. But on my personal web-site no one stops me :)

 C:\MyStuff\Code\Ruby>BinaryBan.rb Krikkit
01001011011100100110100101101011011010110110100101110100

Update

As I thought, I'm far more rusty in Ruby that I'd like to imagine :) Daniele Alessandri got it in way less number of lines via the printf (%b) (see comment below). His code is as follows.

 ARGV.each do |str|
   str.each_byte { |b| printf("%08b", b) }
   puts
end

Comments

  • Anonymous
    December 03, 2006
    What about this simpler and more rubyish implementation?ARGV.each do |str|   str.each_byte { |b| printf("%08b", b) }   putsend
  • Anonymous
    December 03, 2006
    See I knew someone is going to get this far shorter I was not aware of the %b format :)As usual the award goes to Ruby for the most concise the intuitive code...