I was working with BigIntegers to solve a problem on Cody, where I got stuck upon something.
import java.math.*
BigInteger(10)
ans = 10
BigInteger(1234)
ans = -46
BigInteger(num2str(1234))
ans = 1234
I tried to find why this happens but I couldn't find any useful resources. I have no knowledge of Java if anyone needs to know.
Is the default input to BigInteger a string/character array? (Which I suspect so)
Also an odd behaviour (which I don't understand)? Can someone explan why this happens?
for i=1:11
BigInteger(2^i+1)
end
ans = 3 ans = 5 ans = 9 ans = 17 ans = 33 ans = 65 ans = -127 ans = 1 ans = 1 ans = 1 ans = 1

 Réponse acceptée

Walter Roberson
Walter Roberson le 1 Fév 2022

1 vote

The single-parameter form of BigInteger with a numeric parameter is
"BigInteger(byte[] val)
Translates a byte array containing the two's-complement binary representation of a BigInteger into a BigInteger."
So when you pass in a numeric value, it converts the numeric value to a signed byte.
When you pass in the result of num2str() you are using a different constructor,
Translates the decimal String representation of a BigInteger into a BigInteger."

5 commentaires

Dyuman Joshi
Dyuman Joshi le 3 Fév 2022
"Translates a byte array containing the two's-complement binary representation of a BigInteger into a BigInteger."
But it doesn't for all values, as we saw from the loop.
This is from the link you mentioned - "The input array is assumed to be in big-endian byte-order: the most significant byte is in the zeroth element."
Could you please explain this?
Take
x8 = uint8(mod(fix(double(x)),256));
Now construct a numel(x8) * 8 bit number that is mathematically
BigInt = sum(x8 .* (256.^ (numel(x8)-1:-1:0)))
so like .... + x8(end-2) * 256^2 + x8(end-1) * 256^1 + x8(end) * 256^0
so the first element in x8 is the "most significant" (changes the final result by the most), and the last element in x8 is the "least significant" (makes a different of no more than 255)
But mark the integer as being a signed integer. Another way of saying that is
if x8(1) >= 128
BigIntSigned = BigInt - 256^numel(x8)
else
BigIntSigned - BigInt;
end
So when you get to 2^7+1 then that is 129, fix(129) is 129, mod(129,256) is 129. It is the only entry so numel() is 1. It is >= 128, so you take the 129 - 256^1 which is 129 - 256 which is -127 . Which matches
>> BigInteger(129)
ans =
-127
Dyuman Joshi
Dyuman Joshi le 15 Fév 2022
Thanks for the explanation, I understand it much better now.
I have one more question, why 256?
Walter Roberson
Walter Roberson le 15 Fév 2022
One byte holds 8 bits, and 2^8 = 256 .
The BigInteger class always uses full bytes -- you cannot define a BigInteger that is (for example) 11 bits long
Dyuman Joshi
Dyuman Joshi le 15 Fév 2022
That makes it clear, thanks!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

Produits

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by