is it possible to bit mask a char array

怎甘沉沦 提交于 2020-01-17 08:32:27

问题


Let's say I have the following char array

 char array[32];

I want to use only the 10 most significant bits of this array as a hash value.

Is it possible to use bitwise operation on this char array?

If so, how should i do it?


回答1:


Assuming your implementation has 8-bit char, and that you have a 256-bit number stored in big endian in this array, here how to access the 10 msb of the 256-bit number.

uint16_t a;
a = (array[0] << 2 | (array[1] & 0xC0) >> 6) & 0x3FF;  



回答2:


I'm pretty sure you want something like this (again assuming 8-bit chars stored big endian in array):

uint16_t a = (((uint16_t)array[0] & 0xFF) << 2 | ((uint16_t)array[1] & 0xFF) >> 6) & 0x3FF;

To break that down a bit:

uint16_t byte0 = (uint16_t)array[0] & 0xFF;
uint16_t byte1 = (uint16_t)array[1] & 0xFF;
uint16_t a = (byte0 << 2 | byte1 >> 6) & 0x3FF;


来源:https://stackoverflow.com/questions/8862386/is-it-possible-to-bit-mask-a-char-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!