我有一个字节: A :0 B :0 C :0 D :0 E :0 F :0 G :0 H :0
我想以0-31,最快的方式存储一个数字,只使用字符C,D,E,F,G的空格。换句话说,我想将第1位和第2位留空,使用位3 -7存储数字并将第8位清空。
我可以使用c |= 1 << n;设置一个字节的n位c |= 1 << n; 但我不明白如何从pos 2开始?
I have a byte: A:0 B:0 C:0 D:0 E:0 F:0 G:0 H:0
I want to store a number from 0-31, the fastest way, using only the space of characters C, D, E, F, G. In other words, I want to leave the bits 1 and 2 empty, use the bits 3-7 to store the number and have bit 8 empty.
I can set the n bit of a byte using c |= 1 << n; But I fail to understand how to make it start from pos 2?
最满意答案
假设您对可读字符的ASCII范围感兴趣(32-126),则不会有5位的有效范围来满足所需的编码。 例如:
~ (126) = 01111110 (Your Mask) = 01111100因此, ~ (126)与|相同 (124)。
如果您已经以某种方式调整了编码并且可以确保只有低5位的数据,那么您可以简单地使用按位运算:
unsigned char a = your_data; a = (a & 0x1F) << 2; // shift the lower 5 bits over 2 bitsAssuming you are interested in the ASCII range for readable characters (32-126), you will not have the valid range in 5 bits to meet the required encoding. For example:
~ (126) = 01111110 (Your Mask) = 01111100Thus, ~ (126) would be the same as | (124).
If you have somehow already adjusted your encoding and can be assured that you will only have data in the lower 5 bits, than you can simply use bitwise operations:
unsigned char a = your_data; a = (a & 0x1F) << 2; // shift the lower 5 bits over 2 bits更多推荐
发布评论