简体   繁体   中英

C reading bit by bit from char pointer

I have a pointer

char *result

where my linked assembly program writes some data.
I now want to read the data bit by bit from the pointer.
I also know the length of the written data in bit, since my assembly program returned that value.
Is there an easy way to doing this or do i need to interpret it as chars and then bit-shift 8 times per char?

This may be slightly faster than processing it bit-by-bit if the data is very long, by avoiding bit-shifting for all the bytes except the last one, as well as caching:

void process(const char* start, size_t bitlen, void (*f)(char)){
    int i, k;
    register char b;
    for (i = 0; i < bitlen / 8; i++){
        b = start[i];
        f(b & 1);
        f(b & 2);
        f(b & 4);
        f(b & 8);
        f(b & 16);
        f(b & 32);
        f(b & 64);
        f(b & 128);
    }
    b = start[i];
    for (k = 0; k < bitlen % 8; k++){
        f((b>>=1) & 1);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM