Advertisement
Guest User

Untitled

a guest
Oct 16th, 2014
335
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.36 KB | None | 0 0
  1.     public int WriteUTF(string str)
  2.     {
  3.         int strlen = str.Length;
  4.         int utflen = 0;
  5.         int c, count = 0;
  6.  
  7.         for(int i = 0; i < strlen; i++)
  8.         {
  9.             c = str.ToCharArray()[i];
  10.             if((c >= 0x0001) && (c <= 0x007F))
  11.             {
  12.                 utflen++;
  13.             }
  14.             else if(c > 0x07FF)
  15.             {
  16.                 utflen += 3;
  17.             }
  18.             else
  19.             {
  20.                 utflen += 2;
  21.             }
  22.         }
  23.  
  24.         if(utflen > 65535)
  25.         {
  26.             throw new Exception("Encoded string is too long: " + utflen + " bytes");
  27.         }
  28.  
  29.         byte[] bytearr = null;
  30.         bytearr = new byte[(utflen*2) + 2];
  31.  
  32.         bytearr[count++] = (byte) (((uint)utflen >> 8) & 0xFF);
  33.         bytearr[count++] = (byte) (((uint)utflen >> 0) & 0xFF);
  34.  
  35.         int x = 0;
  36.         for(x = 0; x < strlen; x++)
  37.         {
  38.             c = str.ToCharArray()[x];
  39.             if (!((c >= 0x0001) && (c <= 0x007F))) break;
  40.             bytearr[count++] = (byte)c;
  41.         }
  42.  
  43.         for(;x < strlen; x++)
  44.         {
  45.             c = str.ToCharArray()[x];
  46.             if ((c >= 0x0001) && (c <= 0x007F))
  47.             {
  48.                 bytearr[count++] = (byte)c;
  49.             }
  50.             else if (c > 0x07FF)
  51.             {
  52.                 bytearr[count++] = (byte) (0xE0 | ((c >> 12) & 0x0F));
  53.                 bytearr[count++] = (byte) (0x80 | ((c >>  6) & 0x3F));
  54.                 bytearr[count++] = (byte) (0x80 | ((c >>  0) & 0x3F));
  55.             }
  56.             else
  57.             {
  58.                 bytearr[count++] = (byte) (0xC0 | ((c >>  6) & 0x1F));
  59.                 bytearr[count++] = (byte) (0x80 | ((c >>  0) & 0x3F));
  60.             }
  61.         }
  62.         ClientOutput.Write (bytearr, 0, utflen+2);
  63.         return utflen + 2;
  64.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement