将无符号的32位整数拆分为两个可以重建的16位数字 [英] Split Unsigned 32-bit Integer into Two 16-bit numbers that can be rebuilt

查看:677
本文介绍了将无符号的32位整数拆分为两个可以重建的16位数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将Java中的无符号32位Integer拆分为两个单独的16位数字,以后可以将它们加在一起以获得原始数字.

Is it possible to split an unsigned 32 bit Integer in Java, into two separate 16 bit numbers that can later be added together to get the original number.

推荐答案

您可以使用按位运算,包括移位.

You can use bitwise operations, including shifts.

首先拆卸:

int original32 = 1000;
int high16 = original32 >>> 16;
int low16 = original32 & 0xFFFF;
System.out.println(high16);
System.out.println(low16);

在这里,要获得较低的16位,我们只需将该值屏蔽为零输出较高的16位.为了获得更高的16位,我们将其向右移动.

Here, to get lower 16 bits, we just mask the value to zero-out higher 16 bits. To get higher 16 bits, we shift them to the right.

重建:

int rebuilt32 = (high16 << 16) | (low16 & 0xFFFF);
System.out.println(rebuilt32);

在这里,我们将高16位向左移,然后相加"(实际上是或")低位.

Here we shift higher 16 bits back left and then 'add' (actually, OR) lower bits.

这篇关于将无符号的32位整数拆分为两个可以重建的16位数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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