日期:2014-05-18  浏览次数:20952 次

取string ,存入字节数组,如何做?
比如有个string str="abcdef"

将上面的六个字符的str ,, 逐个取出来,存入一个byte数组内

a的ASC码是97,,存入数组时,用16进制存入即:0x61

后面依次类推



------解决方案--------------------
System.Text.Encoding.ASCII.GetBytes
------解决方案--------------------
C# code

            string str = "abcdef";
            byte[] bs = Encoding.ASCII.GetBytes(str);

------解决方案--------------------
我跟过了,是61啊
------解决方案--------------------
string str = "abcdef";
char[] array = str.ToCharArray();
byte[] barray = new byte[array.Length];
for (int i=0;i<array.Length;i++)
{
barray[i] = (byte)array[i];
}
------解决方案--------------------
C# code

var array = "abcdef"
            .Select(x => (Byte)x)
            .ToArray();

------解决方案--------------------
探讨

C# code

var array = "abcdef"
.Select(x => (Byte)x)
.ToArray();

------解决方案--------------------
C# code

        unsafe static void Main(string[] args)
        {
            string str = "abcdef";
            byte[] bs = new byte[str.Length];

            for (int i = 0; i < str.Length; i++)
            {
                bs[i] = (byte)str[i];
                Console.WriteLine("{0:x}", bs[i]);
            }
        }