Niklas
Niklas

Reputation: 33

Java store String in BigInteger

I have to store a string (non-numeric, can contain any UTF8 Chars) in a BigInteger to perform some Mathematical operations with it. I need the conversion to be deterministic which

BigInteger mybigint = new BigInteger(mystring.getBytes());

does not seem to be…

Also I need to be able to convert it back from BigInteger to String. If I convert a String to BigInteger and back it needs to be identical afterwards.

Does anyone have an Idea how to do that? Thank you in advance!

Upvotes: 3

Views: 1887

Answers (2)

Denys Séguret
Denys Séguret

Reputation: 382102

This IS deterministic :

BigInteger mybigint = new BigInteger(mystring.getBytes("UTF-8"));

And you can revert it using

new String(mybigint.toByteArray(), "UTF-8");

I can't exclude there is some kind of usefulness to this process but if you're not sure don't hesitate to mention why you do this.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500065

Don't do this. Fundamentally you don't have numeric information. Don't pretend it's numeric information.

Define what you mean by "mathematical operations" and write a class to perform them. BigInteger is almost certainly the wrong representation here.

Upvotes: 6

Related Questions