C#数字转字节数组类BitConverter

合集下载
相关主题
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

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

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

★源代码:

using System;

using System.Collections.Generic;

using System.Text;

namespace TestBitConvert

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("boolean占1个字节");

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("下面测试int与unit的字节数组的问题,测试低位在前和高位在前情况:");

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} y和z相等:{4}", x, y, z, (long)y-x, y==z);

Console.ReadLine();

}

}

相关文档
最新文档