Reputation: 6199
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
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
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
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:
BitConverter.ToInt32
)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