java 取int型的第二个字节的数

无意中看到某个题目,前提条件,一个byte最多表示256位,因为其是由8个位表示 ,八个1 最多表示256位。

一个int由32位组成,所以是4个byte表示。题目要求是给定一个int数字,问第二个byte是多少。刚开始不会写。

再后来复习nio时,突然想到这题。

1.首先创建 Bytebuffer,其内部是由byte组成的数组。因为我们保存一个int 只需要创建一个大小为4byte的即可。下面看代码。

 
 
  public static void main(String[] args) throws IOException {
        ByteBuffer bb=ByteBuffer.allocate(4); //创建大小为4的byteBuffer
        bb.asIntBuffer().put(5566); //以int视图将任意int数存进去      
        System.out.println(Arrays.toString(bb.array()));    //打印出改bytebuffer,其中想要第几个byte就取出就好了
    }

结果

[0, 0, 21, -66]

2.通过位运算计算,,首先 

int  a=5566;

a=a>>8;

a=a&0xff;

得到的a就是 第二位的值

3.附一个int转byte数组


  private static  byte[] intToByte(int in){
    byte [] b=new byte[4];
    b[3]= (byte) (in&0xff);
    b[2]= (byte) (in>>8 &0xff);
    b[1]= (byte) (in>>16 &0xff);
    b[0]= (byte) (in>>24 &0xff);
    return b;
    }



猜你喜欢

转载自blog.csdn.net/woaiqianzhige/article/details/79954241
今日推荐