Converting signed 16 bit data to unsigned

Ok, need some help on this. If I want to convert 16 bit signed audio data to unsigned, is it as easy as adding 32764 to each sample?

Would squirrel convert each byte if I read it from the blob as signed and wrote it back as unsigned?

I would think at only 16 bit squirrel will have no idea that the number is signed. It will come in with the wrong value and positive.

here is some code to play with. If I have completely murdered the technique hopefully someone will be motivated to help you by correcting me.

`
local actualnegative = -14202;

local highbyte = ((actualnegative>>8) & 0xFF);
local lowbyte = ((actualnegative) & 0xFF);
server.log(highbyte);//returns 200
server.log(lowbyte);//returns 134

server.log ((highbyte<<8) + lowbyte);//returns 51334 - has no idea about signs

local _signed = (((highbyte <<8) + lowbyte)<<16);

_signed = (_signed >>16)

server.log(_signed); // returns -14202

`

The left-shift of 16 puts the bit that holds the sign into the 31st bit position which seems to let squirrel know it is a negative number. When it right-shifts again squirrel retains the sign. I think I saw Peter suggest this trick long ago.

After converting the numbers to the correct sign, then you can add 32764 to each sample and I think that would work out.

a good tool:

http://www.mathsisfun.com/binary-decimal-hexadecimal-converter.html

Add 32768 to each sample, making sure you ignore overflow. Or equivalently, exclusive-OR the top bit with 1:

function s16tou16(b) { b.seek(0, 'b'); for (local i=0; i<b.len()/2; ++i) { local n = b.readn('w'); b.seek(-2, 'c'); b.writen(n ^ 0x8000, 'w'); } }

Peter

edit…

Thanks to you both!

Peter, that works like a charm! I’ve got my Lala board speaking whatever text I send to the AT&T Speech API. I’m setting it up to automatically speak any text data that is sent to it.

I’m having one of those giddy Electric Imp moments. :slight_smile:

@jwehr - if you have the agent code wrapped up in a nice class it would be great to see it in our reference lib :slight_smile:

Yep, I’ll submit as soon as I have it fully fleshed out. There are a few other parameters that the API will accept that I need to complete.