存储号码部分字节,但不是从开始?(Store number in part of byte, but not from start? [closed])

编程入门 行业动态 更新时间:2024-10-28 12:22:12
存储号码部分字节,但不是从开始?(Store number in part of byte, but not from start? [closed])

我有一个字节: 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 bits

Assuming 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) = 01111100

Thus, ~ (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

更多推荐

本文发布于:2023-04-28 07:25:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1330927.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:是从   但不   字节   号码   Store

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!