Skip to content

Instantly share code, notes, and snippets.

@jszmajda
Created July 23, 2010 18:19
Show Gist options
  • Save jszmajda/487823 to your computer and use it in GitHub Desktop.
Save jszmajda/487823 to your computer and use it in GitHub Desktop.
# based on http://code.activestate.com/recipes/528911-barcodes-convert-upc-e-to-upc-a/
class Upc
def self.convert_upc_e_to_upc_a(upce=nil)
return upce if upce.nil? or upce.length < 6 or upce.length > 8 # not a UPC-E
upce = case upce.length
when 6
upce
when 7
upce[0,6]
when 8
upce[1,6]
else
return nil
end
val = "0" + case upce[5,1] # 6th digit
when "0", "1", "2"
upce[0,2] + upce[5,1] + "0000" + upce[2,3] ## 12600 00345
when "3"
upce[0,3] + "00000" + upce[3,2] ## 12300 00045
when "4"
upce[0,4] + "00000" + upce[4,1] ## 12340 00005
else
upce[0,5] + "0000" + upce[5,1] ## 12345 00006
end
val + calculate_check_digit(val).to_s
end
private
def self.calculate_check_digit(v)
chk = 0
v.split(//).each_with_index do |s, i|
chk += s.to_i * (i%2==0 ? 1 : 3)
end
(10 - (chk % 10)) % 10
end
end
@jszmajda
Copy link
Author

in case you ever have to do this too. Converts from things like "01210806" to "012000001086"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment