BString.lua: A utility to convert binary file to Lua strings

I wrote this little Lua script to convert a binary file into a Lua string. This is handy if you want to put PCM sound data in your app, etc.

To use this script copy the code below, and save it to a file named BString.lua (or anything you like), and mark it as executable by issuing the following command line:

chmod +x BString.lua

Now if you wanted to convert a binary file named “HelloWorld.wav” to a string named “hw” in a file named “Sound.lua” then you would write:

./BString.lua HelloWorld.wav Sound.lua hw

Right now it is using string concatenation which isn’t as efficient to load at runtime as other approaches. I will update it later. But I though I would post it now since it is handy

The Script:


#!/usr/bin/env lua

-- Check the command line
if #arg < 1 then
	print("Usage: " .. arg[0] .. " inFile [outFile] [stringName]");
	return;
end

-- Get the in and out filenames
inFName = arg[1];
outFName = arg[2] or (arg[1] .. ".out");
sName = arg[3] or "foo"

-- Read the data
inFile = io.open(inFName, "r");
if not inFile then
	print("Error reading " .. inFName);
	return;
end

data = inFile:read("*all");
inFile:close();

-- Write the binary string
outFile = io.open(outFName, "w+");

newLinePrefix = sName .. ' = ' .. sName .. ' .. "';

outFile:write(sName .. ' = ""\
');
outFile:write(newLinePrefix);		
for pos = 1, #data do
	if pos % 10 == 0 then 
		outFile:write('"\
');		
		outFile:write(newLinePrefix);		
	end
	
	b = string.byte(data, pos);
	outFile:write(string.format("\\\\%i", b));
end
outFile:write('"\
');
outFile:close();

So what exactly am I seeing in that string? Excuse my ignorance, but what could you do with that string in practical terms? When you say PCM audio data, what exactly does that data represent?

Thanks! :slight_smile:

@secondman - this post was written 3 years ago, and JockM is long gone from the forum.

I’ll close this thread - please make a new one if you want to discuss this topic.