#how do i get bits array from a value?

1 messages · Page 1 of 1 (latest)

hearty charm
#

well thats it, i need either an array of booleans(u1) that represent bits of a value that i provided.

void sparrow
#

There isn't language-level support for bit-packed arrays of this form, but you can fairly easily access individual bits with bitwise operations. Do you know what bit endian you're working in?

hearty charm
void sparrow
#

No, bit endian is a detail of what you're doing. Basically, when you're trying to access bits in order, you need to decide whether you want to read the LSB of a byte first, or the MSB of a byte first

hearty charm
#

i really just need to see fourth bit for example, or sixth, something like that

#

So maybe not least significant of most significant bit, maybe something inbetween

void sparrow
hearty charm
#

first bit is LSB

void sparrow
#

Okay, cool - that's bit-little-endian

hearty charm
#

oh great

void sparrow
#

gimme a few moments and i'll write you some simple bit getter/setter functions

hearty charm
#

oh thanks a lot. Much appreciated

void sparrow
#
pub fn getBit(buf: []const u8, idx: usize) bool {
    return (buf[idx / 8] >> @intCast(idx % 8)) & 1 == 1;
}

pub fn setBit(buf: []const u8, idx: usize, val: bool) void {
    if (val) {
        buf[idx / 8] |= @as(u8, 1) << @intCast(idx % 8);
    } else {
        buf[idx / 8] &= ~(@as(u8, 1) << @intCast(idx % 8));
    }
}

Untested but I think this is right

hearty charm
#

okay, i will try, thanks. And for integers i just need to replace 8 with whatever integer length i have?

#

well and types