Zulip Chat Archive
Stream: Is there code for X?
Topic: BitVec n → Vector Bool n
Ka Wing Li (Dec 28 2025 at 07:01):
Is there a function for converting a bit vector to a list of bools?
Ka Wing Li (Dec 28 2025 at 07:02):
The closest thing I can find is
def BitVec.toVector : BitVec n → Vector Bool n := λ bv ↦ bv.toNat.bits.toArray.toVector
But it will not work as docs#Nat.bits will not have leading zeros.
Ka Wing Li (Dec 28 2025 at 07:03):
I am not sure if I am missing something trivial from mathlib.
Matt Diamond (Dec 28 2025 at 07:10):
I think you should be able to get what you need by using docs#List.ofFn along with either docs#BitVec.getLsb or docs#BitVec.getMsb (depending on the ordering you'd like)
Matt Diamond (Dec 28 2025 at 07:14):
you know, something like fun bv => List.ofFn bv.getLsb or whatnot
Ka Wing Li (Dec 28 2025 at 07:17):
Yes, I am trying the function. The tricky part is now the dependent type.
Matt Diamond (Dec 28 2025 at 07:18):
what trouble are you running into?
Ka Wing Li (Dec 28 2025 at 07:19):
Classic trouble of dependent type
Type mismatch
(List.ofFn bv.getMsb).toArray.toVector
has type
Vector Bool (List.ofFn bv.getMsb).toArray.size
but is expected to have type
Vector Bool n
Matt Diamond (Dec 28 2025 at 07:19):
oh, I didn't realize you wanted a vector, you said list (realizing now I should've read the post title more carefully)
Matt Diamond (Dec 28 2025 at 07:19):
just use Vector.ofFn then
Ka Wing Li (Dec 28 2025 at 07:20):
Nice!
Ka Wing Li (Dec 28 2025 at 07:20):
Thanks!
Matt Diamond (Dec 28 2025 at 07:21):
no problem!
Ka Wing Li (Dec 28 2025 at 07:24):
I guess there is also an inverse function as well?
Ka Wing Li (Dec 28 2025 at 07:24):
I am looking up relevant APIs.
Matt Diamond (Dec 28 2025 at 07:27):
yes, it looks like you can use docs#BitVec.ofFnLE (little endian) or docs#BitVec.ofFnBE (big endian) along with docs#Vector.get to go in the other direction
Matt Diamond (Dec 28 2025 at 07:36):
these lemmas should be useful for proving that these transformations are inverse to each other:
https://leanprover-community.github.io/mathlib4_docs/Batteries/Data/BitVec/Lemmas.html
along with docs#Vector.get_ofFn
Last updated: Feb 28 2026 at 14:05 UTC