木子屋 Dnawo's BLOG

C# short,int,long转byte[]

👤 dnawo 📅 2010-01-12 👁 19129 👍 0 💬 0 🔄 本站原创
在做字符串保存为文本时,经常有要求使用n(2,4,8)个字节来保存一个字符,如下边例子:

string content = "木子屋(http://www.mzwu.com/)";

//2字节存储
using (FileStream fs = File.Create(@"c:\test.txt"))
{
    using (BinaryWriter writer = new BinaryWriter(fs))
    {
        for (int i = 0; i < content.Length; i++)
            writer.Write((short)content[i]);
    }
}

//4字节存储
using (FileStream fs = File.Create(@"c:\test2.txt"))
{
    using (BinaryWriter writer = new BinaryWriter(fs))
    {
        for (int i = 0; i < content.Length; i++)
            writer.Write((int)content[i]);
    }
}

//8字节存储
using (FileStream fs = File.Create(@"c:\test3.txt"))
{
    using (BinaryWriter writer = new BinaryWriter(fs))
    {
        for (int i = 0; i < content.Length; i++)
            writer.Write((long)content[i]);
    }
}

若想知道C#将每个字符转成的字节内容,这就需要将short,int,long转成byte[],使用BitConverter.GetBytes方法可以完成这种转换,代码如下:

byte[] b;

//2字节,0x28 0x67
b = BitConverter.GetBytes((short)'木');
for (int i = 0; i < b.Length; i++)
    Console.Write(b[i] + " ");
Console.WriteLine(BitConverter.ToChar(b, 0));

//4字节,0x28 0x67 0 0
b = BitConverter.GetBytes((int)'木');
for (int i = 0; i < b.Length; i++)
    Console.Write(b[i] + " ");
Console.WriteLine(BitConverter.ToChar(b, 0));//注意,ToChar只取2个字节进行转换

//8字节,0x28 0x67 0 0 0 0 0 0
b = BitConverter.GetBytes((long)'木');
for (int i = 0; i < b.Length; i++)
    Console.Write(b[i] + " ");
Console.WriteLine(BitConverter.ToChar(b, 0));

评论(0)

暂无评论。

计算题
评论需审核通过后显示
← 上一篇 页面使用gb2312编码导致IE6、IE7不能显示Google地… 下一篇 → PlatformNotSupportedException: 此…