在Java中获取int的特定位子集 [英] Obtain a specific subset of bits of an int in Java

查看:97
本文介绍了在Java中获取int的特定位子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取Java中int的特定子集(例如5-10位)?

How would I obtain a specific subset, say bits 5-10, of an int in Java?

寻找一种可以在特定位位置通过的方法.我不确定如何创建一个根据输入改变的遮罩,或者即使那是应该如何做的一个遮罩.

Looking for a method where one can pass in specific bit positions. I'm not sure how I would create a mask that changes given the input, or even if that is how one should go about doing it.

我知道这是如何让前台说出一个int的10位:(我认为) int x = num >> 22;

I know this is how one would get the front say 10 bits of an int: (I think) int x = num >> 22;

推荐答案

假设您有一个数字n,并希望位从ij(i = 5,j = 10).

Say you have a number n, and want bits from i to j (i=5, j=10).

请注意,i=0将为您提供最后一点

Note, that i=0 will give you the last bit

 int value = n & (((1 << (j-i)) - 1) << i );

将为您提供结果.

很明显,左边是:您有一个值,并将在其上放置一个位掩码.

The left part is obvious: you have a value, and you will put a bitmask on it.

掩码的值为((1 << (j-i)) - 1) << i.它说:

  • 取一个1位(值:0000000000000001)
  • 向左移动j-i次(值:2 ^(10-5)= 2 ^ 5 = 32 = 0000000000100000)
  • 减去1(值:31 = 0000000000011111)-您看到最低位反转了吗?
  • 向左移动i次(值:31 * 32 = 992 = 0000001111100000)
  • Take a 1 bit (value: 0000000000000001)
  • Shift it left j-i times (value: 2^(10-5) = 2^5 = 32 = 0000000000100000)
  • Deduct 1 (value: 31 = 0000000000011111) - have you seen the lowest bits reversed?
  • Shift it left i times (value: 31*32=992 = 0000001111100000)

因此,您已经获得了5-10位的位掩码(更准确地说,是从5到9,因为不包括第10位).

So, you have got the bitmask for bits 5 - 10 (more precisely, from 5 to 9, since 10th is not included).

这篇关于在Java中获取int的特定位子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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