转移负的BigInteger值-Java [英] Shifting negative BigInteger value - Java

查看:69
本文介绍了转移负的BigInteger值-Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将7字节数组向右移动7位.

I am trying to shift a 7 byte array to the right by 7 bits.

为此,我正在使用BigInteger的shiftright方法.但是,当向右移负的BigInteger时,将添加1的填充或有时删除前导位.

To do this, I am using BigInteger's shiftright method. However, when shifting right for negative BigIntegers, padding with 1s are added or sometimes the leading bit is removed.

以下是执行移位的以下代码:

Here is the following bit of code doing the shifting:

byte[] vcwManD = decryptedVCW;
BigInteger bigIntD = new BigInteger(vcwManD);       // create big int array for shift
BigInteger shiftIntD= bigIntD.shiftRight(7);                // shift right 7 bits
vcwManD = shiftIntD.toByteArray();      

对于二进制的字节数组E865037A9C6424:

For a byte array E865037A9C6424 in binary:

11101000011001010000001101111010100111000110010000100100

11101000011001010000001101111010100111000110010000100100

移位后,我得到二进制的D0CA06F538C8:

When shifted I get D0CA06F538C8 in binary:

110100001100101000000110111101010011100011001000

110100001100101000000110111101010011100011001000

如您所见,它已向右移了7位,但是前导位已被剥离.

As you can see, it has shifted 7 bits to the right, however the leading bit has been stripped.

另一个问题是1填充.对于二进制的字节数组90998951A37908

Another issue is the 1 padding. For byte array 90998951A37908 in binary

10010000100110011000100101010001101000110111100100001000

10010000100110011000100101010001101000110111100100001000

以二进制形式生成FF213312A346F2:

produces FF213312A346F2 in binary:

111111110010000100110011000100101010001101000110111100100

11111111001000010011001100010010101000110100011011110010

这次,开始时已填充了大约7个1.

This time around 7 1's have been padded at the start.

有人知道如何解决这个问题吗?

Does anyone know how to solve this issue?

非常感谢 Shiv

推荐答案

如果要进行移位,则很可能使用长的无符号值而不是有符号值.因此,当您创建BigInteger时,请使用以下构造函数:

If you are doing bit shifts you are likely working with a long unsigned value rather than signed value. So when you create your BigInteger use this constructor:

new BigInteger(1, vcwManD);

这样,可以保证您有一个正数,并且应该可以随心所欲地转移它.

That way you are guaranteed to have a positive number and you should be able to shift it around with no consequence.

这篇关于转移负的BigInteger值-Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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