Otoa

string ascii_array_to_utf8(string byte_array)

Apr 28th, 2024
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // This is to convert a array of ASCII captured in http_resposse() even back a UTF-8 string
  2. string ascii_array_to_utf8(string byte_array)
  3. {
  4.     integer len = llStringLength(byte_array);
  5.     string s;
  6.     integer i;
  7.     while (i < len)
  8.     {
  9.         integer o = llOrd(byte_array, i);
  10.         if (o < 128)
  11.         {
  12.             s += llChar(o);
  13.             i += 1;
  14.         }
  15.         else if (o < 192)
  16.         {
  17.             // Invalid byte for the first byte of a multi-byte character
  18.             s += "�";
  19.             i += 1;
  20.         }
  21.         else if (o < 224 && i + 1 < len)
  22.         {
  23.             // 2-byte character
  24.             s += llChar(((o & 31) << 6) | (llOrd(byte_array, i + 1) & 63));
  25.             i += 2;
  26.         }
  27.         else if (o < 240 && i + 2 < len)
  28.         {
  29.             // 3-byte character
  30.             s += llChar(((o & 15) << 12) | ((llOrd(byte_array, i + 1) & 63) << 6) | (llOrd(byte_array, i + 2) & 63));
  31.             i += 3;
  32.         }
  33.         else if (i + 3 < len)
  34.         {
  35.             // 4-byte character
  36.             s += llChar(((o & 7) << 18) | ((llOrd(byte_array, i + 1) & 63) << 12) | ((llOrd(byte_array, i + 2) & 63) << 6) | (llOrd(byte_array, i + 3) & 63));
  37.             i += 4;
  38.         }
  39.         else
  40.         {
  41.             s += "�";  // Handle cases where the sequence is incomplete
  42.             i += 1;  // Move past the initial byte to prevent endless loop
  43.         }
  44.     }
  45.     return s;
  46. }
Add Comment
Please, Sign In to add comment