How to convert BigInteger to String? - java

I decrypted a data and got a BigInt and when I tried to convert it to string I got some Wired characters.
Code for getting BigInteger
BigInteger dec = process.Decrypt(sec);
Code for getting ByteArray
byte testBy[] = dec.toByteArray();
Code for Converting into String
String ss = new String(testBy);
System.out.println(ss);
and I tried this code too
String ss = new String(testBy);
System.out.println(ss, "UTF8");
I'm getting this output
=^ö½ß‡k+Éæ‚ûŽ3B‚+…Òæ?&¶?kÛUô—c
Help me out here..

BigInteger has a toString() method, which gives a decimal string representation of the value.

A call to System.out.println(dec) should print the decimal representation of dec correctly.
So just make sure that BigInteger dec = process.Decrypt(sec) yields the expected result.

toString() method convert BigInteger to String.Actually it overrides the Object toString() method.Or directly pass BigInteger object to System.out.println() because println bydefault takes Object.toString().

Related

How to go from enum tp byte array and back again?

I have an enum
public enum Test {
VALUE, NAME;
}
I convert it into a byte array
byte[] array = Test.VALUE.toString().getBytes(Charsets.UTF_8)
how can i convert that back into an enum?
Test.valueOf(array.toString()) does not work.
The reason why array.toString didn't work is that toString returns a description of the array, not the string constructed using the bytes in the array with UTF-8 encoding. toString just returns something like [B#60e53b93 which means practically nothing to humans.
To convert a byte array to a string, use the string's constructor, the one that takes a byte array and a Charset. Here's the whole code:
// converting to byte array
Test t = Test.VALUE;
byte[] bytes = t.toString().getBytes(StandardCharsets.UTF_8);
// converting back to Test
String str = new String(bytes, StandardCharsets.UTF_8);
Test newT = Test.valueOf(str);
If you think about it logically, toString can't possibly give you what you expect. This is because to convert a byte array to a string, you need to specify an encoding! You obvious did not pass a Charset object when you call toString, so how on earth is the computer going to know what charset you want?
You have to convert the array back to a proper String first using it constructor. array.toString() does not do what you think and will only return gibberish.
byte[] array = Test.VALUE.toString().getBytes(Charsets.UTF_8);
String valueString = new String(array, Charsets.UTF_8);
Test value = Test.valueOf(valueString);

Converting String to Sha-256 Hash

I want to convert a String to a SHA-256 Hash. I am using this code:
String text = "YOLO";
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(text.getBytes("UTF-8"));
System.out.println(hash.toString());
The problem is, when I start the program, it prints
[B#28d93b30
Why is this, and how can solve this?
Thanks in advance,
Fihdi
As others have mentioned, you're using the default toString() method which simply outputs the class name and hashcode
If you want a hex print out of the contents of the byte array try...
Hex.encodeHexString(byte[] data) from Apache Commons.
Also How to convert a byte array to a hex string in Java? has some examples for doing this without a library.
To print the bytes as hex (instead of that result, explained in How do I print my Java object without getting "SomeType#2f92e0f4"?), simply run:
System.out.println((new HexBinaryAdapter()).marshal(hash));
In JAVA, arrays do not override Object.toString(). Therefore, hash.toString() does not return a representation of the contents of the array, but rather a representation of the array itself. Apparently, this representation of an array is not very useful. The default toString() implementation returns
getClass().getName() + '#' + Integer.toHexString(hashCode())
I have also faced this type of issue and then solve in this way.
String text = "YOLO";
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(text.getBytes(StandardCharsets.UTF_8));
String encoded = DatatypeConverter.printHexBinary(hash);
System.out.println(encoded.toLowerCase());

Convert string to int with 1st null saving

Usually Integer.valueOf(), Integer.parseInt() works perfect. But i have problem if in a String object are some nulls(0), here is some code.
StringBuilder sb = new StringBuilder();
sb.append("0");
sb.append(9);
Integer afterConvert = Integer.valueOf(sb.toString());
System.out.println(afterConvert);
This code shows "9", but i need "09". Is any way to achieve it?
This has nothing to do with null values.
The Integer value of 09 is 9.
If you want to print leasing zeros, use:
System.out.println(String.format("%02d", afterConvert));
See similar question here.
You cannot print Integer with leading 0s like this. You can use NumberFormat class:
NumberFormat nb = NumberFormat.getInstance();
nb.setMinimumFractionDigits(2);
System.out.println(nb.format(afterConvert));

Convert a single byte to a string?

This is simply to error check my code, but I would like to convert a single byte out of a byte array to a string. Does anyone know how to do this? This is what I have so far:
recBuf = read( 5 );
Log.i( TAG, (String)recBuf[0] );
But of course this doesn't work.
I have googled around a bit but have only found ways to convert an entire byte[] array to a string...
new String( recBuf );
I know I could just do that, and then sift through the string, but it would make my task easier if I knew how to operate this way.
You can make a new byte array with a single byte:
new String(new byte[] { recBuf[0] })
Use toString method of Byte
String s=Byte.toString(recBuf[0] );
Try above , it works.
Example:
byte b=14;
String s=Byte.toString(b );
System.out.println("String value="+ s);
Output:
String value=14
There's a String constructor of the form String(byte[] bytes, int offset, int length). You can always use that for your conversion.
So, for example:
byte[] bite = new byte[]{65,67,68};
for(int index = 0; index < bite.length; index++)
System.out.println(new String(bite, index,1));
What about converting it to char? or simply
new String(buffer[0])
public static String toString (byte value)
Since: API Level 1
Returns a string containing a concise, human-readable description of the specified byte value.
Parameters
value the byte to convert to a string.
Returns
a printable representation of value.]1
this is how you can convert single byte to string try code as per your requirement
Edit:
Hows about
""+ recBuf[0];//Hacky... not sure if would work
((Byte)recBuf[0]).toString();
Pretty sure that would work.
Another alternate could be converting byte to char and finally string
Log.i(TAG, Character.toString((char) recBuf[0]));
Or
Log.i(TAG, String.valueOf((char) recBuf[0]));
You're assuming that you're using 8bit character encoding (like ASCII) and this would be wrong for many others.
But with your assumption you might just as well using simple cast to character like
char yourChar = (char) yourByte;
or if really need String:
String string = String.valueOf((char)yourByte);

How to convert BigInteger to String in java

I converted a String to BigInteger as follows:
Scanner sc=new Scanner(System.in);
System.out.println("enter the message");
String msg=sc.next();
byte[] bytemsg=msg.getBytes();
BigInteger m=new BigInteger(bytemsg);
Now I want my string back. I'm using m.toString() but that's giving me the desired result.
Why? Where is the bug and what can I do about it?
You want to use BigInteger.toByteArray()
String msg = "Hello there!";
BigInteger bi = new BigInteger(msg.getBytes());
System.out.println(new String(bi.toByteArray())); // prints "Hello there!"
The way I understand it is that you're doing the following transformations:
String -----------------> byte[] ------------------> BigInteger
String.getBytes() BigInteger(byte[])
And you want the reverse:
BigInteger ------------------------> byte[] ------------------> String
BigInteger.toByteArray() String(byte[])
Note that you probably want to use overloads of String.getBytes() and String(byte[]) that specifies an explicit encoding, otherwise you may run into encoding issues.
Use m.toString() or String.valueOf(m). String.valueOf uses toString() but is null safe.
Why don't you use the BigInteger(String) constructor ? That way, round-tripping via toString() should work fine.
(note also that your conversion to bytes doesn't explicitly specify a character-encoding and is platform-dependent - that could be source of grief further down the line)
You can also use Java's implicit conversion:
BigInteger m = new BigInteger(bytemsg);
String mStr = "" + m; // mStr now contains string representation of m.
When constructing a BigInteger with a string, the string must be formatted as a decimal number. You cannot use letters, unless you specify a radix in the second argument, you can specify up to 36 in the radix. 36 will give you alphanumeric characters only [0-9,a-z], so if you use this, you will have no formatting. You can create: new BigInteger("ihavenospaces", 36)
Then to convert back, use a .toString(36)
BUT TO KEEP FORMATTING:
Use the byte[] method that a couple people mentioned. That will pack the data with formatting into the smallest size, and allow you to keep track of number of bytes easily
That should be perfect for an RSA public key crypto system example program, assuming you keep the number of bytes in the message smaller than the number of bytes of PQ
(I realize this thread is old)
To reverse
byte[] bytemsg=msg.getBytes();
you can use
String text = new String(bytemsg);
using a BigInteger just complicates things, in fact it not clear why you want a byte[]. What are planing to do with the BigInteger or byte[]? What is the point?
String input = "0101";
BigInteger x = new BigInteger ( input , 2 );
String output = x.toString(2);
//How to solve BigDecimal & BigInteger and return a String.
BigDecimal x = new BigDecimal( a );
BigDecimal y = new BigDecimal( b );
BigDecimal result = BigDecimal.ZERO;
BigDecimal result = x.add(y);
return String.valueOf(result);
https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html.
Every object has a toString() method in Java.

Categories