amin

amin

  • NA
  • 5
  • 20k

C# ascii to hex conversion

Nov 21 2011 4:26 AM
Hi All,

I needed to send hex data to epson printer as below. This command is to print barcode.

1D 6b 43 0c 36 31 32 33 34 35 33 37 37 30 39 31

For this example, the highlighted part are 12 digit I need to send.

I've prepared below program which works just fine.

        static void Main(string[] args)
        {
            SendSampleData();
        }

        private static void SendSampleData()
        {
            SerialPort port = new SerialPort(
                "COM1", 9600, Parity.None, 8, StopBits.One);
            // Open the port for communications
            port.Open();

            //1D 6b 43 0c 36 31 32 33 34 35 33 37 37 30 39 31
            port.Write(new byte[] { 0x1D, 0x6b, 0x43, 0x0c,
                0x36, 0x31, 0x32, 0x33, 0x34, 0x35, 0x33, 0x37, 0x37, 0x30, 0x39, 0x31},
                0, 16);
            port.Write("612345377091");
            port.Write(new byte[] { 0x0A }, 0, 1);

            port.Close();
        }

But now I wanted to simplify it to work as in code below... basically I imagine it so that I only need to adjust the barCodeString "6123453770918" value and the subsequent code will handle it to send the command like shown above.

I imagine that the code need to convert the string it to hex value and have each assigned to an array. The array will then be used to send a command to the printer.

I am still new to .NET and C#. I will appreciate any help to get a working code.

        private static void SendSampleData()
        {
            string barCodeString = "6123453770918"; //12 digit but not fixed
            byte[] bHex;


            SerialPort port = new SerialPort(
                "COM1", 9600, Parity.None, 8, StopBits.One);
            // Open the port for communications
            port.Open();
           
           stringToHexArray(barCodeString); //I dont have the code //assign ascii string to bHex[] byte array

            //1D 6b 43 0c 36 31 32 33 34 35 33 37 37 30 39 31
            port.Write(new byte[] { 0x1D, 0x6b, 0x43, 0x0c,
                bHex[0],  bHex[1],  bHex[2],  bHex[3],  bHex[4],  bHex[5],  bHex[6],  bHex[7],  bHex[8],  bHex[9],  bHex[10],  bHex[11]},
                0, 16);
            port.Write("612345377091");
            port.Write(new byte[] { 0x0A }, 0, 1);

            port.Close();
        }

I've searched the net for ascii to hex conversion, but main problem I have is that I dont know C# and .NET. I will appreciate your kind help in getting a code that works and I will try to work backward to understand the program back... :(



Answers (4)