Make it Better
C# 十六进制Hex处理类 Unity中Hex转换
2016-10-7 StanWind


拿java写的类改的 可用于Unity

using System.Collections;
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Threading;
/*
* 字符转换工具类
* By StanWind
*/
public class NumberUtils{
//字节集到十六进制文本
public static String byteToHexString(byte[] bytes) {
StringBuilder stringBuilder = new StringBuilder(32);
//Debug.Log ("L---->" + bytes.Length);
for (int i = 0; i < bytes.Length; i++) {

int v = bytes[i] & 0xFF;
//String hv = Integer.toHexString(v).toUpperCase();
//C#写法
string hv = v.ToString ("X2").ToUpper();

if (hv.Length < 2) {
stringBuilder.Append(0);
}
stringBuilder.Append(hv+" ");
}
return stringBuilder.ToString();
}
//字节集到十六进制文本 带长度
public static String byteToHexStringWithLength(byte[] bytes) {
StringBuilder stringBuilder = new StringBuilder(32);
//Debug.Log ("L---->" + bytes.Length);
int l = bytes.Length & 0xFF;
string hv = l.ToString ("X2").ToUpper();

if (hv.Length < 2) {
stringBuilder.Append(0);
}
stringBuilder.Append(hv+" ");

for (int i = 0; i < bytes.Length; i++) {

int v = bytes[i] & 0xFF;
//String hv = Integer.toHexString(v).toUpperCase();
//C#写法
hv = v.ToString ("X2").ToUpper();

if (hv.Length < 2) {
stringBuilder.Append(0);
}
stringBuilder.Append(hv+" ");
}
return stringBuilder.ToString();
}

//十六进制文本到字节集
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || "".Equals(hexString)) {
return null;
}
// 去除空格、制表符、换行、回车
hexString = hexString.Replace("\\s*|\t|\r|\n", "").ToUpper();
hexString = hexString.Replace(" ", "");

int length = hexString.Length / 2;
char[] hexChars = hexString.ToCharArray();
byte[] bytes = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
byte t = (byte)(charToByte (hexChars [pos]) << 4 | charToByte (hexChars [pos + 1]));
bytes[i] = t;
//print(t);
}
return bytes;
}

public static int hexToInt(string data){
string r = data.Replace (" ", "");
return Convert.ToInt32 (r, 16);
}

public static byte[] stringToBytes(string input){
//System.Text.Encoding gbkEncode = System.Text.Encoding.GetEncoding("gb2312");
return Encoding.GetEncoding("gb2312").GetBytes(input);
}
public static string bytesToString(byte[] b){
return Encoding.GetEncoding("gb2312").GetString (b);
}

public static byte charToByte(char i) {
return (byte) "0123456789ABCDEF".IndexOf(i);
}

public static string read(string data,int start,int length){
string rtn = data.Replace(" ","");

rtn = rtn.Substring (start * 2, length * 2);
//Debug.Log (rtn);
rtn = appendSpace (rtn);
return rtn;
}

public static string appendSpace(string data){
StringBuilder sb = new StringBuilder ();
for (int i = 1; i < (data.Length / 2); i++) {
sb.Append(data.Substring(i*2-2,2));
sb.Append (" ");
}
sb.Append (data.Substring (data.Length - 2, 2));

return sb.ToString ();
}
}

发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容