C#数字转字节数组类BitConverter

发布时间:2012-12-08 15:44:06

BitConverter用于基础数据类型与字节数组相互转换

vs2005中,新建控制台应用程序TestBitConvert,测试静态类BitConverter的使用情况。

★源代码:

using System;

using System.Collections.Generic;

using System.Text;

namespace TestBitConvert

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("boolean1个字节");

bool[] bl = new bool[] { true, false };

for (int j = 0; j < bl.Length; j++)

{

byte[] bufferC = BitConverter.GetBytes(bl[j]);

string s = string.Empty;

for (int i = 0; i < bufferC.Length; i++)

{

s += (s.Length == 0 ? "" : ",") + bufferC[i];

}

Console.WriteLine("[{0}]转换为字节数组为:{1}", bl[j], s);

}

Console.WriteLine();

Console.WriteLine("字符转换为2个字节.(C#中字符时unicode编码,2个字节)");

char[] ch = new char[] { 'A', '' };

for (int j = 0; j < ch.Length; j++)

{

byte[] bufferC = BitConverter.GetBytes(ch[j]);

string s = string.Empty;

for (int i = 0; i < bufferC.Length; i++)

{

s += (s.Length == 0 ? "" : ",") + bufferC[i];

}

Console.WriteLine("字符[{0}]转换为字节数组为:{1}", ch[j], s);

}

Console.WriteLine();

Console.WriteLine("double类型转换为8个字节");

double[] dl = new double[] { 21.3, 12.345, 1.0, 8, 1.59 };

for (int j = 0; j < dl.Length; j++)

{

byte[] bufferC = BitConverter.GetBytes(dl[j]);

string s = string.Empty;

for (int i = 0; i < bufferC.Length; i++)

{

s += (s.Length == 0 ? "" : ",") + bufferC[i];

}

Console.WriteLine("[{0}]转换为字节数组为:{1}", dl[j], s);

}

Console.WriteLine();

Console.WriteLine("下面测试intunit的字节数组的问题,测试低位在前和高位在前情况:");

Console.WriteLine("本地计算机的字节顺序是否是低位在前:{0}", BitConverter.IsLittleEndian);//是否低位在前

int number = 88888888;

byte[] buffer = BitConverter.GetBytes(number);//低位在前:本机的默认设置

string s1 = "";

for (int i = 0; i < buffer.Length; i++)

{

s1 += buffer[i].ToString("X2");//低位在前

}

string s2 = Convert.ToString(number, 16);//高位在前

string s3 = number.ToString("X8");//高位在前

Console.WriteLine("s1={0},s2={1},s3={2}", s1, s2, s3);

int x = -1234567890;

byte[] bytes = BitConverter.GetBytes(x);

Console.Write("整数转化为字节数组为:");

for (int i = 0; i < bytes.Length; i++)

{

Console.Write(bytes[i] + ",");

}

Console.WriteLine();

uint y = BitConverter.ToUInt32(bytes, 0);

uint z = (uint)x;

Console.WriteLine("x={0},y={1},z={2}, y-x={3} yz相等:{4}", x, y, z, (long)y-x, y==z);

Console.ReadLine();

}

}

}

★程序执行效果如图:

C#数字转字节数组类BitConverter

相关推荐