int in binary, octal and hexadecimal

In this chapter you will learn:

  1. hexadecimal int
  2. Octal int
  3. Format integer as hexadecimal
  4. Format integer as octal and binary numbers

hexadecimal int

To specify a hexadecimal constant, begin with 0x or 0X, followed by a sequence of digits in the range 0 through 9 and a (or A) through f (or F).

Hexadecimal digits a (or A) through f (or F) represent values in the range 10 through 15.

using System;/*  j  a  v a 2 s .co m*/

public class MainClass{
    public static void Main() {
        int i = 0x3fff;   // Hexadecimal constant
        int j = 0X3FFF;   // Equal to i
        Console.WriteLine(i);
        Console.WriteLine(j);

    }
}

Octal int

To specify an octal constant, begin the specification with 0, followed by a sequence of digits in the range 0 through 7.

using System;//  j a  va 2  s.  co  m

public class MainClass{
    public static void Main() {
        //The digits 8 and 9 are errors in specifying an octal constant.
        int i = 0377;   // Octal constant
        int j = 0397;   // Error: 9 is not an octal digit
        Console.WriteLine(i);
        Console.WriteLine(j);
    }
}

Format integer as hexadecimal

using System;//from j  a  v a  2s.com
using System.Globalization;

public class Example
{
   public static void Main()
   {
      int[] numbers = { -111, 0, 169, 11111 };
      foreach (int number in numbers) {
         // Display value as hexadecimal.
         Console.Write("{0,12:X2}", number);
      }
   }
}

The code above generates the following result.

Format integer as octal and binary numbers

using System;//from  j  a  v  a  2s . c o m
using System.Globalization;

public class Example
{
   public static void Main()
   {

      int[] numbers = { -1, 111111, 22222222 };
      Console.WriteLine("{0,8}   {1,32}   {2,11}   {3,10}", "Value", "Binary", "Octal", "Hex");
      foreach (int number in numbers) {
         Console.WriteLine("{0,8}   {1,32}   {2,11}   {3,10}", 
                           number, Convert.ToString(number, 2), 
                           Convert.ToString(number, 8), 
                           Convert.ToString(number, 16));
      }      
   }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. C# long type
Home » C# Tutorial » Byte, Integer, Long
Integer Family
Integer ranges
byte
Convert to byte
Parse string to byte
byte format
byte octal and hexadecimal
byte binary operation
byte overflow with unchecked
int
int value
Compare int value
int calculation
int value overflow
int binary operation
Parse string to int value
Format int value
int in binary, octal and hexadecimal
long
long value calculation
ulong