2

I want to write a BigInteger to a file, but I want to prepend it with the lenght of the integer, so I know how long it is when I read it again (the file wih have several bigints)

I know I can convert it to a byte array using bigInteger.toByteArray(), but then to prepend this array with its length the only way I can think of is to create another array and copy it. I don't want to do that since it will basically double the time I would take to write the file, and waste time and memory.

Is there any other, more efficient method?

Edit: Looking at the comments - I'm doing this because I want to put multiple bigints in a single file, and so I can use the length as delimiter of sorts.

0

1 Answer 1

3

You don't have to prepend anything to the array. Write the length first, and the array right after that.

Sign up to request clarification or add additional context in comments.

5 Comments

How do I find the lenght before I create the array?
You don't have to know the length beforehand. BigInteger.toByteArray takes care of creating an array of the right size, fills it up and returns it.
But that is not what I want at all. Say, the bigint is 256, then the byte array return by BigInteger.toByteArray will be 00000001 00000000, but what I want is 00000010 00000001 00000000
@hoodakaushal sure, so just get the byte array, write its length, and then write it. There's no memory overhead in temporarily storing the array in a variable.
Oh, by write you mean to the file. Makes sense now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.