Any bit type available in rust ? u8 is byte type , but i need a bit type

all we know u8 is byte type , but i need bit type just like blow

struct Directives {
version: u8, // 1 byte
padding: bit, // 4 bit
encryption_method: bit, // 4 bit

}

1 Like

Rust doesn't have bitfields. You can just use bit operations (shifts and masks) to extract the relevant bits from integer types.

4 Likes

thansk :100: :pray:

I think you could use the bitfield crate for this.
Example from the readme:

bitfield!{
    struct IpV4Header(MSB0 [u8]);
    u32;
    get_version, _: 3, 0;
    get_ihl, _: 7, 4;
    get_dscp, _: 13, 8;
    get_ecn, _: 15, 14;
    get_total_length, _: 31, 16;
    get_identification, _: 47, 31;
    get_df, _: 49;
    get_mf, _: 50;
    get_fragment_offset, _: 63, 51;
    get_time_to_live, _: 71, 64;
    get_protocol, _: 79, 72;
    get_header_checksum, _: 95, 79;
    get_source_address, _: 127, 96;
    get_destination_address, _: 159, 128;
}

Also have a look at the documentation and the provided examples.

Edit: modular-bitfield looks much better documented and user-friendly.

1 Like

Thanks a lot

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.