Byte array to Integer (vice versa)
1: public static int BytesToInt(byte[] bytes)
2: {
3: return int.Parse(BytesToString(bytes).Trim());
4: }
5:
6: public static string BytesToString(byte[] bytes)
7: {
8: ASCIIEncoding enc = new System.Text.ASCIIEncoding();
9: return enc.GetString(bytes);
10: }
1: public static byte[] IntToBytes(int value)
2: {
3: ASCIIEncoding enc = new System.Text.ASCIIEncoding();
4: return enc.GetBytes(value.ToString());
5: }
Code Snippet
- /// <summary>
- /// Bytes to Integer
- /// </summary>
- /// <param name=”src”></param>
- /// <returns></returns>
- public static int BytesToInt(byte[] src)
- {
- if (src.Length == 1)
- return (int)src[0];
- else if (src.Length <= 2)
- return BitConverter.ToInt16(src, 0);
- return BitConverter.ToInt32(src, 0);
- }