OSDP.Net 5.2.1
A .NET library for implementing the Open Supervised Device Protocol (OSDP)
Loading...
Searching...
No Matches
BinaryUtils.cs
1using System;
2using System.Collections;
3using System.Collections.Generic;
4using System.Linq;
5using System.Text;
6
7namespace OSDP.Net.Utilities;
8
13public static class BinaryUtils
14{
20 public static BitArray HexStringToBitArray(string hex) =>
21 HexStringToBitArray((IEnumerable<char>)hex);
22
28 public static BitArray HexStringToBitArray(IEnumerable<char> hex) =>
29 new(HexToBytes(hex).Select(x => BinaryExtensions.ReverseBits(x)).ToArray());
30
39 public static IEnumerable<byte> HexToBytes(IEnumerable<char> seq)
40 {
41 using var enumerator = seq.GetEnumerator();
42
43 while (enumerator.MoveNext())
44 {
45 if (enumerator.Current is '-' or ' ')
46 {
47 if (!enumerator.MoveNext()) throw new InvalidOperationException("Not a valid hex string");
48 }
49
50 var a = enumerator.Current.HexToInt();
51 if (!enumerator.MoveNext()) throw new InvalidOperationException("Not a valid hex string");
52 var b = enumerator.Current.HexToInt();
53
54 // .NET's BitArray reads array of bytes in Least Significant Bit (LSB) first.
55 // However, the way we use this thing and to make it compatible with human-
56 // readable hex strings, we want to store data as MSB first.
57 yield return ((byte)((a << 4) | b));
58 }
59 }
60
66 public static string BitArrayToString(BitArray arr)
67 {
68 var builder = new StringBuilder();
69 foreach (bool bit in arr)
70 {
71 builder.Append(bit ? "1" : "0");
72 }
73
74 return builder.ToString();
75 }
76}
Extension methods for helping with binary conversion.
static byte ReverseBits(this byte value)
Reverse the bits of a single byte.
Helper routines for manipulating binary representations of data that are used within the OSDP....
static string BitArrayToString(BitArray arr)
Convert the BitArray instance to a binary string representation.
static BitArray HexStringToBitArray(IEnumerable< char > hex)
Convert a sequence of hex digit characters into BitArray.
static BitArray HexStringToBitArray(string hex)
Convert a string containing hex digits into BitArray.
static IEnumerable< byte > HexToBytes(IEnumerable< char > seq)
Convert a sequence of hex digit characters into their byte representation.