【问题标题】:C# convert string to byte and ouput as stringC#将字符串转换为字节并输出为字符串
【发布时间】:2016-06-26 23:01:05
【问题描述】:

我想将string 转换为byte 并将其输出为string

示例: 字符串:255 输出:0xFF

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

我得到的是System.Byte[] 而不是值。

【问题讨论】:

  • 我想你是说你想将一个完全由十进制数字组成的字符串转换为一个字符串,该字符串表示从 0 到 255 的数值,用“0x”表示该值的十六进制(大写)前缀。

标签: c# string type-conversion byte


【解决方案1】:

没有数组可以做到这一点。你必须自己写。类似于下面的代码:

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);

【讨论】:

    猜你喜欢
    • 2019-10-10
    • 1970-01-01
    • 2014-11-03
    • 1970-01-01
    • 2016-01-21
    • 1970-01-01
    • 1970-01-01
    • 2014-04-29
    • 1970-01-01
    相关资源
    最近更新 更多