From: Jan Svitok Date: 2007-01-30T04:31:00+09:00 Subject: Re: Problem with Base64 decoding On 1/29/07, alexander wrote: > hi there, > last time i accidentely posted this question as a reply to another one.. > i�m really sorry for that. i will not make that mistake again. > > so here�s my question again in a fresh new thread :) > > i�m having a small problem with base64 decoding a string. > i�m porting a php script over to ruby and the decoding gives me > different results in ruby and in php. the problem is that the php > results works for the processing i do afterwards while the ruby version > doesn�t. > here�s the scripts in question: > > php: > > $bytes = file_get_contents("test.rgb"); > $bitmap = base64_decode($bytes); > > $header = ""; > $header .= "\xFF\xFE"; > $header .= pack("n2",120,97); > $header .= "\x01"; > $header .= "\xFF\xFF\xFF\xFF"; > > $header .= $bitmap; > > file_put_contents("test_php.gd",$header); > ?> > > ruby: > require 'rubygems' > require 'fileutils' > require 'base64' > > all_bytes = Base64.decode64(IO.read("test.rgb")) > > bitmap = "\xFF\xFE" > bitmap << [120,97].pack("n2") > bitmap << "\x01" > bitmap << "\xFF\xFF\xFF\xFF" > bitmap << all_bytes > > File.new("test_ruby.gd","w").puts(bitmap) > > the ruby version is one byte shorter. > > i�m probably missing something rather obvious here, but any pointers to > how i can make the ruby output be like the php output would be greatly > appreciated :) > > i�ve uploaded the test.rgb file i�m using to here: > > http://rss.fork.de/test.rgb if that�s even needed :) Hi, 1. have a look at the differences in those two files. By that you should be able to tell where's the problem: either in the decoding part or in the assembling. 2. you are using puts that appends a newline, so it seems to me that ruby version is one byte LONGER. if that's the problem, replace puts with write. 3. File.open("test_ruby.gd","w") {|f| f.puts(bitmap) } should be safer, as it doesn't rely on garbage collector for closing the file, it is closed immediately after the block finishes. This will be helpful when you'll work with large number of files (and you'll run out of free descriptors) 4. I guess you don't need rubygems nor fileutils for this to work (that's ok if you use them for some other code not posted)