c# 字符串转化成字节

zhanggd614 2009-11-07 12:56:07
我有组字节
假设位 byte[] by = new byte[]{ 0x1d, 0x9b, 0x63, 0xc9, 0x33, 0xda, 0xe6, 0x62 };

现在 有个字符串 string str = "1d9b63c933dae662";

怎么样把这个字符串转换成和给定的by字节数组给定的值相同
...全文
219 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
liherun 2009-11-07
  • 打赏
  • 举报
回复
up
yyz985 2009-11-07
  • 打赏
  • 举报
回复
'A' - 'A' = 0; 0 + 10 = 10 A转换成10
'B' - 'A' = 1; 1 + 10 = 11 B转换成11
zhanggd614 2009-11-07
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 yyz985 的回复:]

byte getValueFromHex(char value)
{
return value >= 'A' : value - 'A' + 10 : value - '0';
}
[/Quote]

没明白 这个判断语句
zhanggd614 2009-11-07
  • 打赏
  • 举报
回复
c#转换就是比较麻烦 一切计算都要转化成整型
yyz985 2009-11-07
  • 打赏
  • 举报
回复
Convert不是很好用的,Convert来Convert去很麻烦
zhanggd614 2009-11-07
  • 打赏
  • 举报
回复
谢谢 liherun 原来Convert.ToInt32(,)第二个参数是这么用的
yyz985 2009-11-07
  • 打赏
  • 举报
回复
byte[] GetHexStringBytes(string str)
{
byte[] bytes = new bytes[str.length / 2];
int p = 0;
IEnumerator<char> ie = str.GetEnumerator();
while(ie.MoveNext())
{
byte currentValue = getValueFromHex(ie.Current);
ie.MoveNext();
byte nextValue = getValueFromHex(ie.Current);
bytes[p++] = currentValue | 0x10 + nextValue;
}
return bytes;
}
byte getValueFromHex(char value)
{
return value >= 'A' : value - 'A' + 10 : value - '0';
}
liherun 2009-11-07
  • 打赏
  • 举报
回复
byte[] by = new byte[] { 0x1d, 0x9b, 0x63, 0xc9, 0x33, 0xda, 0xe6, 0x62 };
byte[] by1 = new byte[8];
string str= "1d9b63c933dae662";
if (str.Length % 2 == 1||str.Length==0)
return;
for (int i = 0; i < str.Length / 2; i++)
{
by1[i]=(Byte)Convert.ToInt32(str.Substring(i*2, 2), 16);
}
yyz985 2009-11-07
  • 打赏
  • 举报
回复
string getHexString(byte[] bytes)
{
char[] buff = new char[bytes.Length * 2];
int p = 0;
foreach(byte b in bytes)
{
buff[p++] = ToHexChar(b & 0x10);
buff[p++] = ToHexChar(b % 0x10);
}
return new string(buff);
}

char ToHexChar(byte b)
{
return b < 10 ? '0' + b: 'A'+b-10;
}

110,536

社区成员

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

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

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