简体   繁体   中英

C# convert string to byte and ouput as string

I want to convert a string to byte and output it as string .

example: string: 255 output: 0xFF

richTextBox1.AppendText(textBox1.Text + " || " + Convert.ToBytes(textBox1.Text) + "\n");

I am getting System.Byte[] instead of the value.

There's no implementation for an array to do that. You'll have to write your own. Something like the code below:

byte[] bytes = new byte[] { 1, 2, 3, 4, 5, 6 };
            string output = string.Empty;
            foreach (byte item in bytes)
            {
                output += Convert.ToString(item, 16).ToUpper().PadLeft(2,'0');

            }
            Console.WriteLine(output);
            //or using string.Format
            bytes = new byte[] { 1, 2, 3, 14, 15, 16 };
             output = string.Empty;
            foreach (byte item in bytes)
            {
                output = string.Format("{0},{1:X}", output, item);

            }
            Console.WriteLine(output);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM