How to convert a sequence of 32 char (0/1) to 32 bits (uint32_t)?

前端 未结 3 1970
既然无缘
既然无缘 2021-01-27 00:29

I have an array of char (usually thousands of bytes long) read from a file, all composed of 0 and 1 (not \'0\' and \'1\', in which case I could use strtoul). I want

3条回答
  •  时光取名叫无心
    2021-01-27 00:51

    Bit shifting is the simplest way to go about this. Better to write code that reflects what you're actually doing rather than trying to micro-optimize.

    So you want something like this:

    char bits[32];
    // populate bits
    uint32_t value = 0;
    for (int i=0; i<32; i++) {
        value |= (uint32_t)(bits[i] & 1) << i;
    }
    

提交回复
热议问题