lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Jeff Wise wrote:
> In my continuing saga of PDF’s and raster images, I need to translate
> names (like John Smith) from ASCII to EBCDIC. Thus ‘Abcd’ (hex =>
> X’41626364’) would become X’C1828384’.

EBCDIC? Ack! Do people really still use that?

> Usually this is done with a table lookup, i.e. the character to be
> translated is used as a binary offset into a 256 byte table of the
> translated characters. Thus at position X’41’ in this table would be
> x’C1’ facilitating the translation of the ASCII ‘A’ into its EBCDIC
> equivalent. How does one go about doing this in Lua?

The simplest solution is to just set up an associative array.

local ascii_to_ebcdic = {
	["A"] = string.char(0xC1),
	["b"] = string.char(0x82),
	["c"] = string.char(0x83),
	["d"] = string.char(0x84)
}

Then you can convert a single character with:

local ebcdic = ascii_to_ebcdic[ascii]

You can convert a complete string with:

local ebcdics = string.gsub(asciis, ".", function (s)
	return ascii_to_ebcdic[s]
end)

(Depending on what you're doing it may be more worthwhile using numbers
in the associative array, but it's probably not worth it.)

-- 
David Given
dg@cowlark.com