BitArray writes the various bits in order as if you were reading, ie. the first bit is bit-7 of the first byte, the eight bit is bit-0 of the first byte, the 9th bit is bit-7 of the second byte etc. So the minimal solution is that you have to invert the bitness (instead of power(2, i)
, do power(2, 64 - i)
. Of course, as you've observed, this is very limited. One option, that will work up to your 64 bits, is to simply use a bigger data type - bigint
. However, for anything larger than 64 bits, you're back where you started.
For a more general solution, you want to use the binary field on a per-byte basis. You can use the substring
function for this.
select
substring(binaryValue, ceiling(cast(@bit as decimal) / 8), 1)
& power(2, @bit % 8);
This gives you a zero if the specified bit is not set, and a non-zero value if it is.
The key here is that the string functions actually work for binary / image as well, so you can eg. access any byte at will just by using substring :)