-3

I would like to create a console app that can cycle through a range of base 16 numbers.

e.g.

for(int i = 0; i < FFFF; i++)
{
    // do work
}

Is this possible?

drewwyatt
  • 5,989
  • 15
  • 60
  • 106
  • 1
    http://stackoverflow.com/questions/74148/how-to-convert-numbers-between-hexadecimal-and-decimal-in-c – TyCobb Aug 22 '14 at 18:42

4 Answers4

7

You can use hexadecimal integer literal:

for(int i = 0; i < 0xFFFF; i++)
{
    // do work
}

See C# specification 2.4.4.2 Integer literals

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
3

Hex values are prefixed by 0x in C# (and many other languages), so you can do this:

for (int i = 0; i < 0xFFFF; i++) {
   // do work
}
entropic
  • 1,683
  • 14
  • 27
2

Numbers are numbers regardless of base. Base is just a representational convention. The loop

for ( int i = 0 , i < 65536 ; ++i )
{
}

iterates over the set of integers with the domain 0 <= x <= 65535. The set is the same, whether its represented in base-10, base-16, base-2 and base-11 or some other base (the Babylonians liked base-12).

If you want to specify a value in base-16, use a hex literal: 0x1234. Note that the literal's type is dependent on its value (for the details of which see the documentation). If you want or need to coerce the literal to have a specific type, use the appropriate literal suffix (for instance, 0x1234UL will give you an ulong).

If you want to display a value in base-16, you need to format it appropriately:

string formatted = string.Format("The decimal value 1,234 is 0x{0:X8}" , 1234 ) ;

For details, see Standard Numeric Format Strings and Custom Numeric Format Strings.

Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135
0

OK, I'll feed it... As in many languages, hex literals in C# are prefixed with 0x.

for(int i = 0; i < 0xFFFF; i++)
{
    // do work
}

Of course, i isn't a "base 16 number". It's an integer. The binary representation is going to be base two, unless .NET has been ported to more exotic architectures than I've imagined. At any time, you can stringify i as hex, octal, binary, or anything you like.