1

How to convert unsigned BigInteger into unsigned byte when the value is higher?

String value = "202";
BigInteger a = new BigInteger( value );
Byte b = new BigInteger( value ).byteValue() // returns -54

How to get unsigned byte value from BigInteger?

Pratap A.K
  • 4,337
  • 11
  • 42
  • 79
  • 3
    There's no such thing as an "unsigned byte" type in Java. The `byte` type is *always* signed. This is entirely separate to `BigInteger` - you'd see the same behaviour if you cast an `int` value of 202 to `byte`. – Jon Skeet Nov 02 '18 at 12:23
  • As it is unlikely that you are really going to store `byte`-sized numbers in `BigInteger`-s, you might consider describing what you are planning to do with that number afterwards. – tevemadar Nov 02 '18 at 12:30
  • @tevemadar after that I need to compare this number with database stored value. – Pratap A.K Nov 02 '18 at 12:38
  • @JonSkeet in general how can I store and retrieve values which are > 128 – Pratap A.K Nov 02 '18 at 12:39
  • Why `byte` and `BigInteger` then? Are you aware of functions like `Integer.parseInt()`? You could very well write `int i = Integer.parseInt(value);`, and compare that to the number you have in DB. And if your numbers grow large, remember that `BigInteger` has a [`compareTo`](https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#compareTo(java.math.BigInteger)) method. – tevemadar Nov 02 '18 at 12:42

2 Answers2

1

you should cast "202" to int because java does not have unsigned byte. I suppose .intValue() would help

star67
  • 1,505
  • 7
  • 16
1

Maybe you looking for something like this:

import java.math.*;
public class MyClass {
    public static void main(String args[]) {
        String value = "202";
        BigInteger a = new BigInteger( value );
        Byte b = new BigInteger( value ).byteValue() ;
        System.out.println(a);
        System.out.println(unsignedToBytes((byte)b));
    }

    public static int unsignedToBytes(byte b) {
    return (int)b & 0xFF;
  }
}

and here is a very good explanation: Can we make unsigned byte in Java

nerd100
  • 97
  • 1
  • 8