欢迎光临

木子屋

标题: C# short,int,long转byte[]

作者: dnawo

日期: 2010-01-12 04:41 PM

分类: Web编程

内容: 在做字符串保存为文本时，经常有要求使用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)

登录

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 2.043 ms

返回

标题: C# short,int,long转byte[]

你没有权限发表评论

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 2.043 ms

返回

暂无评论

返回

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 2.123 ms

返回