C#中如何把byte[]数组转换成其他类型

superct 2003-03-16 04:52:05

byte[] bytes = new byte[256];
//receive some stream from network
该bytes头四个字节是Int32型的数据,之后是由某个特定的分隔符分隔的几个字符串,请问我如何将该字节数组的内容读出?
...全文
1028 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
dragontt 2003-03-17
  • 打赏
  • 举报
回复
byte[] bytes = new byte[256];
MemoryStream ms = new MemoryStream( bytes );
StreamReader sr = new StreamReader(ms);
string s = sr.ReadToEnd();
///
用Convert类体供的方法,转成你需要的类型
timmy3310 2003-03-17
  • 打赏
  • 举报
回复
a = (int)bytes[0];
b = (int)bytes[1];
c = (int)bytes[2];
d = (int)bytes[3];

int r = (int)(a*0x1000+b*0x100+c*0x10+d);

这四个字节分别是存放Int数组不同位的值,我们拿10进制数值做个比方,例如一个数组:
int[] a = int[4]
{ 1,2,3,4 };
//如果要把这四个整数组合成一个整数,那么:
int result = a[3]*1000+a[2]*100+a[1]*10+a[0];
//这样 result 就等于1234

字节数组中存放的是16进制的数值,所以运算的时候采用16进制运算,但是原理和10进制的数值是一样的,不知这样你懂了吗
duying 2003-03-17
  • 打赏
  • 举报
回复
精彩
superct 2003-03-17
  • 打赏
  • 举报
回复
谢谢timmy3310(tim)的讲解

给分。
caosheng 2003-03-16
  • 打赏
  • 举报
回复
System.Convert.ToInt32()
System.Convert.ToInt16()
System.Convert.ToString()

......
等函数有以一个byte的参数你去看看吧
areliang 2003-03-16
  • 打赏
  • 举报
回复
你用一个循环,依次转换。再一一附个一个你要的数组就可以了
superct 2003-03-16
  • 打赏
  • 举报
回复
To timmy3310(tim): 不是很懂您的代码,能给我解释一下吗?谢谢。
timmy3310 2003-03-16
  • 打赏
  • 举报
回复
不好意思,虽然结果是一样,但是代码改成这样比较好

int r = (int)( bytes[0]*0x1000+bytes[1]*0x100+bytes[2]*0x10+bytes[3] )
timmy3310 2003-03-16
  • 打赏
  • 举报
回复
a = (int)bytes[0];
b = (int)bytes[1];
c = (int)bytes[2];
d = (int)bytes[3];

int r = (int)(a*0x1000+b*0x100+c*0x10+d);
superct 2003-03-16
  • 打赏
  • 举报
回复
to: timmy3310(tim):
谢谢。可能是我说得不太清楚,头四个字节是一个Int32类型的整数,不是4个。
我主要就是想把这个整数取出来,字符串的我知道怎么取。
timmy3310 2003-03-16
  • 打赏
  • 举报
回复
byte[] bytes = new byte[256];
//receive some stream from network

int a,b,c,d;
string theStr;

a = (int)bytes[0];
b = (int)bytes[1];
c = (int)bytes[2];
d = (int)bytes[3];

byte[] newBytes = byte[bytes.Length-4];
for( int i=0;i<newBytes.Length;i++ )
newBytes[i] = bytes[i+4];

theStr = System.Text.Encoding.Default.GetString( newBytes ); //注意你接受的字符串的编码,根据编码这里要使用不同的编码来获得字符串

//如果字符串是已','分割
string[] stringValues = theStr.Split( ',' );

//stringValues这个数组就是分割后的各个字符串
yqdeng 2003-03-16
  • 打赏
  • 举报
回复
直接用ToString()不行吗?
DannyChen 2003-03-16
  • 打赏
  • 举报
回复
Convert.To.....(你看看那些方法,有个是直接转成string行的)

110,556

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧