First, you can convert the value to the string "01" using WorksheetFunction.Dec2Bin . Then replace each "0", "1" with the code 0 or 1 and pass the result to the Byte array:
Public Function ToBitArray(ByVal value As Long) As Byte() Dim str As String str = WorksheetFunction.Dec2Bin(value) ' "101" str = Replace(Replace(str, "0", ChrW(0)), "1", ChrW(1)) ' "\u0001\u0000\u0001" ToBitArray = StrConv(str, vbFromUnicode) ' [1, 0, 1] End Function
But Dec2Bin limited to 511, and working with strings is quite expensive. Therefore, if your goal is to get maximum performance, then you should use a loop to read each bit:
Public Function ToBitArray(ByVal value As Long) As Byte() Dim arr(0 To 31) As Byte, i As Long i = 32& Do While value i = i - 1 arr(i) = value And 1 value = value \ 2 Loop ToBitArray = MidB(arr, i + 1) ' trim leading zeros End Function
source share