Geeks With Blogs
Andy Johns' Blog Andy's twisted brain....

Someone asked me a question about coercing hex values greater than int.MaxValue into signed ints.... Basically they were wondering if there was a type suffix to mark the hex as a signed int so it would be read by the compiler as a negative number.... there isn't. The way to do this is to use the unchecked statement and cast the uint value as an int..... I wrote the below code to demonstrate, and as I haven't seen anything quite like this out there I'm posting it..... If it helps you drop me a comment I love to hear it....

-----Start a new C# console app and paste this code in place of the default----
using System;
namespace UncheckedExample
{
 class DemoUnchecked
 {
  // Andy Johns 6/7/2004
  [STAThread]
  static void Main(string[] args)
  {
   //demonstrates use of unchecked
   int maxValuePlus, hexMax, unsignedMax, unsignedMaxPlus = 0;

   // Basically unchecked suppresses overflow checking.
   // bits above the maximum size of the type are dropped.
   // for documentation of unchecked see:
   // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vclrfunchecked.asp
   unchecked
   {
    // unsigned int values above MaxValue (2147483647)
    // cast as signed ints become negative
    // until uint.MaxValue (4294967295) which equals signed int -1.
    // Values above that have the high bit dropped off
    // (because of the unchecked statement) and thus become zero again
    // i.e. 4294967296 == 0.
    maxValuePlus = int.MaxValue + 1;
    hexMax = (int) 0x80000000;
    unsignedMax = (int) uint.MaxValue;
    unsignedMaxPlus = (int) uint.MaxValue + 1;
   }
   Console.WriteLine("Unchecked integer operations.....");
   Console.WriteLine("int.MaxValue = {0}", int.MaxValue);
   Console.WriteLine("int.MaxValue + 1 = {0}", maxValuePlus);
   Console.WriteLine("0x80000000 cast as int = {0}", hexMax);
   Console.WriteLine("uint.MaxValue cast as int = {0}", unsignedMax);
   Console.WriteLine("uint.MaxValue + 1 cast as int = {0}", unsignedMaxPlus);
   Console.ReadLine(); // to pause the output....
  }
 }
}

-------------------------

-Andy

Posted on Monday, June 7, 2004 9:02 PM | Back to top


Comments on this post: Unchecked and Signed/Unsigned Ints

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Andy Johns | Powered by: GeeksWithBlogs.net