从一个字节抓取n位 [英] Grabbing n bits from a byte

查看:182
本文介绍了从一个字节抓取n位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从一个字节中抢取n位有点麻烦.

I'm having a little trouble grabbing n bits from a byte.

我有一个无符号整数.假设我们的十六进制数字为0x2A,十进制为42.用二进制形式,它看起来像是:00101010.我将如何获取前5位(即00101)和后3位(即010),并将它们放入单独的整数中?

I have an unsigned integer. Let's say our number in hex is 0x2A, which is 42 in decimal. In binary it looks like this: 0010 1010. How would I grab the first 5 bits which are 00101 and the next 3 bits which are 010, and place them into separate integers?

如果有人可以帮助我,那就太好了!我知道如何从一个字节中提取内容,而这只是简单地做

If anyone could help me that would be great! I know how to extract from one byte which is to simply do

int x = (number >> (8*n)) & 0xff // n being the # byte

我在栈上的另一篇文章中看到的

溢出,但是我不确定如何从字节中取出单独的位.如果有人可以帮助我,那就太好了!谢谢!

which I saw on another post on stack overflow, but I wasn't sure on how to get separate bits out of the byte. If anyone could help me out, that'd be great! Thanks!

推荐答案

整数在机器内部表示为位序列;对于人类来说幸运的是,编程语言提供了一种机制来向我们显示这些数字以十进制(或十六进制),但是不会改变它们的内部表示形式.

Integers are represented inside a machine as a sequence of bits; fortunately for us humans, programming languages provide a mechanism to show us these numbers in decimal (or hexadecimal), but that does not alter their internal representation.

您应该修改按位运算符&|^~以及移位运算符<<>>,这将帮助您了解如何解决此类问题.

You should revise the bitwise operators &, |, ^ and ~ as well as the shift operators << and >>, which will help you understand how to solve problems like this.

整数的最后3位是:

x & 0x7

从最后8位开始的5位是:

The five bits starting from the eight-last bit are:

x >> 3    // all but the last three bits
  &  0x1F // the last five bits.

这篇关于从一个字节抓取n位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆