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)
暂无评论。