1

I have this chunk of code

long num = Int64.Parse(Convert.ToString(random.Next(0, 65535), 2).PadLeft(16, '0'))

When using this code the string is not padded with the leading zeros. I'm not sure, but my guess is maybe when the string is parsed it removes the leading zeros from some reason?

If I do something like this

long num = Int64.Parse(Convert.ToString(random.Next(0, 65535), 2).PadLeft(16, '8'))

or any number that isn't zero, it will come out correctly to 16 digits with leading 8's.

Is there a good explanation to why this is happening?

Also is there a quick easy fix?

This is not a duplicate of anything using int.ToString("D16") or anything of that sort. I believe this is a unique problem.

Timmy
  • 543
  • 1
  • 7
  • 19

2 Answers2

5

You're padding a string with 0, then converting to an integer, so of course any leading zeros will be removed.

Ie.

000000123 == 123

While padding with 8 works, because you are creating a new number:

888888123 != 123

If you want the number padded with 0, just remove the Int64.Parse.

Steve
  • 9,335
  • 10
  • 49
  • 81
1

You can use string instead of long

string num = Convert.ToString(random.Next(0, 65535), 2).PadLeft(16, '0');

Thanks

Nitika Chopra
  • 1,281
  • 17
  • 22