Last active
November 17, 2017 08:14
-
-
Save chinaq/63e4c84d037c2d92cd8cf355ba787d59 to your computer and use it in GitHub Desktop.
C# Data Helper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[TestClass] | |
public class QData | |
{ | |
############################### | |
# str hex to int 32 | |
##################### | |
public static int StrHexToInt(string hexStr) | |
{ | |
return Convert.ToInt32(hexStr.Replace(" ", ""), 16); | |
} | |
# ------------------ | |
[TestMethod] | |
public void HexStrToInt_Positive() | |
{ | |
string hexStr = "00 00 01 0C "; | |
int result = QData.StrHexToInt(hexStr); | |
Assert.AreEqual(268, result); | |
} | |
[TestMethod] | |
public void HexStrToInt_Negitive() | |
{ | |
string hexStr = "F0 00 01 0C "; | |
int result = QData.StrHexToInt(hexStr); | |
Assert.AreEqual(-268435188, result); | |
} | |
############################# | |
# bytes to str hex | |
################### | |
public static string BytesToStrHex(byte[] bytes, string separator=" ") | |
{ | |
string hexStr = BitConverter.ToString(bytes); | |
if (separator != "-") | |
hexStr = hexStr.Replace("-", separator); | |
return hexStr; | |
} | |
######################### | |
# 4 bytes to int 32, 大端在前 | |
#################### | |
public static int Bytes4ToInt(byte[] bytes, int start) | |
{ | |
if (BitConverter.IsLittleEndian) | |
Array.Reverse(bytes); | |
return BitConverter.ToInt32(bytes, start); | |
} | |
# -------------- | |
[TestMethod] | |
public void Bytes4ToInt() | |
{ | |
byte[] bytes = new byte[] { 0xF0, 0x00, 0x01, 0x0C }; | |
int result = QData.Bytes4ToInt(bytes, 0); | |
Assert.AreEqual(-268435188, result); | |
} | |
######################### | |
# 4 bytes to long, 大端在前 | |
################## | |
public static long Bytes4ToLong(byte[] bytes, int start) | |
{ | |
if (BitConverter.IsLittleEndian) | |
Array.Reverse(bytes); | |
return BitConverter.ToUInt32(bytes, start); | |
} | |
# ------------------------ | |
[TestMethod] | |
public void Bytes8ToLong() | |
{ | |
byte[] bytes = new byte[] { 0x00, 0x11, 0xFD, 0x41 }; | |
long result = QData.Bytes4ToLong(bytes, 0); | |
Assert.AreEqual(1178945, result); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment