hs2d
hs2d

Reputation: 6199

Generate random int using random byte generator

I m using random generator what takes the length of random bytes as an input and returns byte array. What i need now is to convert that byte array to 8 digit integer and from that to a string.

byte[] randomData = this.GetRandomArray(4);
SecretCode = Math.Abs(BitConverter.ToInt32(randomData, 0)).ToString().Substring(0, 7);

But some occasions the int is shorter than 8 digits and my method fails. How can i make sure that the byte array generated can be converted to 8 digi int number?

Upvotes: 0

Views: 1225

Answers (4)

Floris
Floris

Reputation: 46415

One more option:

myString = BitConverter.ToUInt32(randomData, 0).toString("D8");

Note - using ToUInt32 is a more sensible approach than converting to signed integer and taking the absolute value (it also doubles the number of values you can generate since -123 and 123 will result in a different string output, which they won't if you use Math.Abs.); and the format "D8" should convert to eight digits including leading zeros.

See https://stackoverflow.com/a/5418425/1967396

Upvotes: 1

Shawn C
Shawn C

Reputation: 356

You need to concatenate eight zeros before trying to take the Substring(), then take the last 8 characters.

StringBuffer s = new StringBuffer("00000000").append(Math.Abs(BitConverter.ToInt32(randomData, 0)).ToString());
SecretCode = s.substring(s.length()-7);

Your other option is to use a formatter to ensure the stringification of the bits returns leading zeros.

Upvotes: 0

Mutation Person
Mutation Person

Reputation: 30520

Are you sure that your method is failing on the Substring? As far as I can see there's a number of issues:

  1. It'll fail if you don't get 4 bytes back (ArgumentException on BitConverter.ToInt32)
  2. It'll fail if the string isn't long enough (your problem from above)
  3. It'll truncate at seven chars, not eight, as you want.

You can use the PadLeft function to pad with zeros. If want eight then code should look like:

var s = Math.Abs(
           BitConverter.ToInt32(randomData, 0))
               .ToString()
               .PadLeft(8, '0')
               .Substring(0, 8);

For seven, replace the 8 with a 7.

Upvotes: 0

borkovski
borkovski

Reputation: 978

You could just use <stringCode>.PadLeft(8, "0")

Upvotes: 1

Related Questions