Text To Byte Conversion
| LSL Portal | Functions | Events | Types | Operators | Constants | Flow Control | Script Library | Categorized Library | Tutorials |
Here's a function to pass a string of text and receive a list of bytes. A second function is provided to work in reverse. These methods are especially useful for working with encryption.
Text2Bytes.lsl
<lsl> string base64characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; list text2bytes(string text) {
string base64 = llStringToBase64(text);
list bytes;
integer i;
integer n = llStringLength(base64);
for(i = 0; i < n; i += 4)
{
integer dword = llBase64ToInteger(llGetSubString(base64, i, i + 3) + "AA") >> 8;
bytes += (dword & 0xFF0000) >> 16;
bytes += (dword & 0xFF00) >> 8;
bytes += dword & 0xFF;
}
return bytes;
} string bytes2text(list bytes) {
string text;
integer i;
integer n = llGetListLength(bytes);
for(i = 0; i + 2 < n; i += 3)
{
integer b1 = llList2Integer(bytes, i);
integer b2 = llList2Integer(bytes, i + 1);
integer b3 = llList2Integer(bytes, i + 2);
integer bbb = (b1 & 0xff) << 16 | (b2 & 0xFF) << 8 | (b3 & 0xFF);
text += llGetSubString(base64characters, (bbb & 0x00FC0000) >> 18, (bbb & 0x00FC0000) >> 18);
text += llGetSubString(base64characters, (bbb & 0x0003F000) >> 12, (bbb & 0x0003F000) >> 12);
text += llGetSubString(base64characters, (bbb & 0x00000FC0) >> 6, (bbb & 0x00000FC0) >> 6);
text += llGetSubString(base64characters, (bbb & 0x0000003F) >> 0, (bbb & 0x0000003F) >> 0);
}
if(n - i > 0 && n - 1 > 3)
{
integer two = n - i - 1;
integer b1 = llList2Integer(bytes, i);
integer b2 = llList2Integer(bytes, i + 1);
integer bbb = (b1 & 0xff) << 16;
if(two) bbb = bbb | (b2 & 0xFF) << 8;
text += llGetSubString(base64characters, (bbb & 0x00FC0000) >> 18, (bbb & 0x00FC0000) >> 18);
text += llGetSubString(base64characters, (bbb & 0x0003F000) >> 12, (bbb & 0x0003F000) >> 12);
if(two)
text += llGetSubString(base64characters, (bbb & 0x00000FC0) >> 6, (bbb & 0x00000FC0) >> 6);
else
text += "=";
text += "=";
}
return llBase64ToString(text);
}
default {
state_entry()
{
list bytes = text2bytes("Hello, Avatar!");
llSay(0, llList2CSV(bytes));
string text = bytes2text(bytes);
llSay(0, text);
}
touch_start(integer total_number)
{
list bytes = text2bytes("Touched.");
llSay(0, llList2CSV(bytes));
string text = bytes2text(bytes);
llSay(0, text);
}
}
</lsl>