1

I am trying to encode Arabic text to hex in order to send it to a POS printer.

 byte[] bytes1 = Encoding.UTF8.GetBytes("عمر");
    Array.Reverse(bytes1);
    var hexString = BitConverter.ToString(bytes1);
    hexString = hexString.Replace("-", "");


    MyPrinter.PrintAr(hexString);

but I still get the wrong hex format that my printer understand. I need the format should look like:

\uFEA3

I also tried below code:

byte[] bytes1 = Encoding.Unicode.GetBytes("عمر");
         Array.Reverse(bytes1);
        int counter = 0;
        var value=""     ;
        string var2 = "";
        foreach (byte letter in bytes1)
        {
            // Get the integral value of the character.


            // Convert the decimal value to a hexadecimal value in string form.
            if (counter == 0)
            {

                counter = 1;
                  value =  letter.ToString() ;
            }
            else
            {
                value += letter.ToString();
                var2 = Convert.ToUInt16(value).ToString();
                insert = "\\u" + var2;
                counter = 0;
            }

            hexOutput += insert;


        } 

but still getting hex with number format like:

\u0669

Would you please help to get the right hex format for my printer.

  • https://stackoverflow.com/questions/1615559/convert-a-unicode-string-to-an-escaped-ascii-string – Ulugbek Umirov Aug 16 '18 at 18:40
  • thanks, but none of them returned similar to \uFEA3. all I get is similar to \u0669 which is not what I need. – abdulrahman albeladi Aug 16 '18 at 19:21
  • You cannot get character codes out of a string that doesn't contain them. Arabic orthography is too tricky for me to make the call, but if you what that output then you need a string literal like "\ufea3". Or to put it another way, your program has to do the job that the OS text renderer normally does. – Hans Passant Aug 16 '18 at 21:35

1 Answers1

0

You can use this. It encodes the Unicode text to a string group. Every character is compiled to a 4-bit hex number:

string textInput = "عمر"
StringBuilder stringBuilder = new StringBuilder();
foreach (char character in textInput)
{
    stringBuilder.Append(Convert.ToString(character, 16).PadLeft(4,'0'));
}
string hex = stringBuilder.ToString();

I hope this is what you need :)

Ehsan Mohammadi
  • 1,168
  • 1
  • 15
  • 21