简体   繁体   中英

c++ - Convert an int array of 8 positions to char

I have an int array of 8 positions representing 8 bits.

int zBits[8]={0, 1, 1, 1, 1, 0, 1, 0};

zBits array is the character "z" in bits ("7a" in hex) ( http://www.utf8-chartable.de/ ).

How can I convert this int array (zBits) in the "z" char using c++?

The most straightforward way to do this is directly:

char z = (zBits[7]     ) |
         (zBits[6] << 1) |
         (zBits[5] << 2) |
         (zBits[4] << 3) |
         (zBits[3] << 4) |
         (zBits[2] << 5) |
         (zBits[1] << 6) |
         (zBits[0] << 7);

If you like, you can reformulate this into a loop which will be slightly shorter.

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