(Java)将负的short的比特放入整数 [英] (Java) Put negative short's bits to an interger

查看:46
本文介绍了(Java)将负的short的比特放入整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在32位整数的尾部放入一个短整数(16位)(我正在将一些小范围的数字压缩为唯一的整数).但是没有找到比下面更好的方法了,我必须使用两次操作,这会更好吗?

I want to put a short integer (16 bits) into tail of a 32 bits integer (I'm compressing some small-range numbers to an unique integer). But didn't found a better looking way than bellow, I have to use two operation, can it be better?

short sh = -1; // 16 bits 1
int zip = 0; // last 16 bits presents a short number

System.out.println("Wrong way, maybe many of us will try first:");
zip |= sh; // expect 0xffff
System.out.println(Integer.toHexString(zip)); // but 0xffffffff

System.out.println("Simple way, right but looks ugly, two operations");
zip = 0;
zip |= sh << 16 >>> 16; // expect 0xffff
System.out.println(Integer.toHexString(zip)); // yeah

System.out.println("Is there a nicer looking way, one operation for example?");

推荐答案

Java中所有按位运算都是使用int或long进行的,因此您在这里没有太多选择.并强制转换一个设置了符号位的较短基本类型,即可将符号位扩展"到所有新创建的"位.

All bitwise operations in Java are done using ints or longs, therefore you don't have too much choice here; and casting a shorter primitive type whose sign bit is set will "expand" the sign bit to all "newer created" bits.

有一种解决方案可以一行"地完成,但仍将是两个操作:

There is a solution to do it "in one line", but that will still be two operations:

zip |= (sh & 0xffff);

请注意,它几乎要求zip开头为0,或者至少它的16个低位为0.

Note, it pretty much requires that zip is 0 to start with, or at least that its 16 low bits are 0.

这篇关于(Java)将负的short的比特放入整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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