0

Having the following block in C#

using (var nuq = new RNGCryptoServiceProvider())
{
    var data = new byte[4];
    nuq.GetBytes(data);
    return BitConverter.ToUInt32(data, 0).ToString(CultureInfo.InvariantCulture);
}

I want to convert this in Java. So far I have:

SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
var data = new byte[4];
random.nextBytes(data);

I don't know the Java equivalent of BitConverter.

How can I convert data to UInt32?

Nikolay Kostov
  • 16,433
  • 23
  • 85
  • 123
sarbo
  • 1,661
  • 6
  • 21
  • 26
  • Well, you can't really do that since there is no uint32 in Java. You'd have to use a `long`. Or Guava's `UnsignedInts`. – fge Feb 16 '15 at 10:22
  • Ok, and how can I do that? Can you give me an example? – sarbo Feb 16 '15 at 10:56

1 Answers1

0

When you get your random you can return a call to a method that converts the bytes to a long, something like:

public long bytesToLong(byte[] bytes) {
    ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
    buffer.put(bytes);
    buffer.flip();//need flip 
    return buffer.getLong();
}
aviad
  • 8,229
  • 9
  • 50
  • 98