0

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?

hs2d
  • 6,027
  • 24
  • 64
  • 103
  • I'd set some constraints on MSB bytes, for example a minimum value so generated integer will be big enough (8 digits or more). As alternative you may generate a new number when what you have doesn't satisfy that criterion. – Adriano Repetti Apr 08 '14 at 13:11

4 Answers4

1

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

borkovski
  • 938
  • 8
  • 12
1

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

Community
  • 1
  • 1
Floris
  • 45,857
  • 6
  • 70
  • 122
0

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.

James Wiseman
  • 29,946
  • 17
  • 95
  • 158
0

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.

Shawn C
  • 356
  • 2
  • 5