[转]C#中string与byte[]的转换帮助类

本文介绍了一个C#帮助类,用于简化字符串(string)与字节数组(byte[])之间的转换过程,尤其针对DES和TripleDES加密算法的老代码移植工作。提供了多个实用函数,如从字符串到字节数组(str2arr),从字节数组到字符串(arr2str),以及十六进制与ASCII之间的相互转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在写c#程序时,string和byte[]之间的转换比较烦,在移植一些老程序时感觉很不好。我在c#中使用des和tripledes时移植一块老代码时也遇到了同样的情况。为了下次不为同样的事情烦恼,就写了下面的帮助类。 
主要实现了以下的函数 


代码中出现的sidle是我的网名。 

/* 
* @author wuerping 
* @version 1.0 
* @date 2004/11/30 
* @description: 
*/
 
using system; 
using system.text; 
namespace sidlehelper 

/// <summary> 
/// summary description for strhelper. 
/// 命名缩写: 
/// str: unicode string 
/// arr: unicode array 
/// hex: 二进制数据 
/// hexbin: 二进制数据用ascii字符表示 例 字符1的hex是0x31表示为hexbin是 31 
/// asc: ascii 
/// uni: unicode 
/// </summary> 

public sealed class strhelper 

hex与hexbin的转换 

#region 数组和字符串之间的转化 
public static byte[] str2arr(string s) 

return (new unicodeencoding()).getbytes(s); 
}
 
public static string arr2str(byte[] buffer) 

return (new unicodeencoding()).getstring(buffer, 0, buffer.length); 
}
 

public static byte[] str2ascarr(string s) 

return system.text.unicodeencoding.convert(system.text.encoding.unicode, 
system.text.encoding.ascii, 
str2arr(s)); 
}
 

public static byte[] str2hexascarr(string s) 

byte[] hex = str2ascarr(s); 
byte[] hexbin = hex2hexbin(hex, hex.length); 
return hexbin; 
}
 
public static string ascarr2str(byte[] b) 

return system.text.unicodeencoding.unicode.getstring( 
system.text.asciiencoding.convert(system.text.encoding.ascii, 
system.text.encoding.unicode, 
b) 
); 
}
 

public static string hexascarr2str(byte[] buffer) 

byte[] b = hex2hexbin(buffer, buffer.length); 
return ascarr2str(b); 
}
 
#endregion
 
}
 
}
 
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值