十六进制字符串转化成字符串输出HexToStr(Delphi版、C#版)
2016-04-07 15:15
585 查看
//注意:Delphi2010以下版本默认的字符编码是ANSI,VS2010的默认编码是UTF-8,delphi版得到的字符串须经过Utf8ToAnsi()转码才能跟C#版得到的字符串显示结果一致。
//Delphi版:
function HexToStr(str: string): string; function HexToInt(hex: string): integer; var i: integer; function Ncf(num, f: integer): integer; var i: integer; begin Result := 1; if f = 0 then exit; for i := 1 to f do result := result * num; end; function HexCharToInt(HexToken: char): integer; begin if HexToken > #97 then HexToken := Chr(Ord(HexToken) - 32); Result := 0; if (HexToken > #47) and (HexToken < #58) then { chars 0....9 } Result := Ord(HexToken) - 48 else if (HexToken > #64) and (HexToken < #71) then { chars A....F } Result := Ord(HexToken) - 65 + 10; end; begin result := 0; hex := ansiuppercase(trim(hex)); if hex = '' then exit; for i := 1 to length(hex) do result := result + HexCharToInt(hex[i]) * ncf(16, length(hex) - i); end; var s, t: string; i, j: integer; p: pchar; begin s := ''; i := 1; while i < length(str) do begin t := str[i] + str[i + 1]; s := s + chr(hextoint(t)); i := i + 2; end; result := s; end;
//********************************************************************
C#版:
///<summary> /// 从16进制转换成汉字 /// </summary> /// <param name="hex"></param> /// <param name="charset">编码,如"utf-8","gb2312"</param> /// <returns></returns> public string HexToStr(string hex, string charset) { if (hex == null) throw new ArgumentNullException("hex"); hex = hex.Replace(",", ""); hex = hex.Replace("\n", ""); hex = hex.Replace("\\", ""); hex = hex.Replace(" ", ""); if (hex.Length % 2 != 0) { hex += "20";//空格 } // 需要将 hex 转换成 byte 数组。 byte[] bytes = new byte[hex.Length / 2]; for (int i = 0; i < bytes.Length; i++) { try { // 每两个字符是一个 byte。 bytes[i] = byte.Parse(hex.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber); } catch { // Rethrow an exception with custom message. throw new ArgumentException("hex is not a valid hex number!", "hex"); } } System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset); return chs.GetString(bytes); }
相关文章推荐
- Delphi 实现16进制转字符串及字符串(中文)转16进制
- 关于Delphi字符串内存泄露的问题
- 深入了解Delphi 7中的四种消息框
- Windows的自带控件(比如TButton)大多数消息都由它自己处理,Delphi覆盖了那么多WM_函数优先级较低,一般用不上
- DELPHI异步选择模型UDP
- WM_ERASEBKGND官方解释(翻译),以及Delphi里所有的使用情况(就是绘制窗口控件背景色,并阻止进一步传递消息)
- Jedi项目,还真得好好看看,有许多控件和新封装的API(Delphi里面没有)
- 虚继承之单继承的内存布局(VC在编译时会把vfptr放到类的头部,这和Delphi完全一致)
- Delphi CreateProcess
- delphi FillChar的用法(转)
- Delphi GDI+基本用法总结
- delphi多线程设计
- Delphi中WebBrowser拦截网页Alert对话框消息(转)
- Delphi中Indy 10的安装和老版本的卸载
- delphi7 手动安装 indy10.2.3
- Delphi 高效读写锁
- Delphi 最小化程序到任务栏托盘 增加右键PopMenu
- delphi实现函数/过程
- Delphi开发的数据库程序在C:\PDOXUSRS.NET生成文件,拒绝访问及读写权限
- Delphi自写组件:可设置颜色的按钮(改成BS_OWNERDRAW风格,然后CN_DRAWITEM)