Skip to content

Instantly share code, notes, and snippets.

@dmoulton
Created October 26, 2010 20:03
Show Gist options
  • Save dmoulton/647665 to your computer and use it in GitHub Desktop.
Save dmoulton/647665 to your computer and use it in GitHub Desktop.
Returns a binary representation of a POSTNET encoded zip code, suitable for converting to an image
#returns binary representation of a POSTNET encoded zip code
#could be used to filter a zip code and then generate an image
#1 = full bar, 0 = half bar
class PostnetBin
def self.convert(zip)
codes = ["11000","00011","00101","00110","01001","01010","01100","10001","10010","10100"]
r = "1" #bookend
total = 0
zip.gsub(/[^\d]/,'').each_char do |c|
r += codes[c.to_i]
total += c.to_i
end
#check digit
#find sum of digits, get next highest number divisible by 10
#check digit is difference between that number and the original total
check = (((total/10) + 1) * 10) - total
r += codes[check]
r + "1" #bookend
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment