Click here to Skip to main content
14,699,491 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am trying to output my code with 32 zeroes of padding... My code works fine without the padding. When I do pad, it gives me the error "unhandled exception: System.NullReferenceException: Object reference not sset to an instance of an object....

What can I do to fix this?

using System;

class Binary
    public static string Bin(uint number)

        if( number / 2 == 0)
            Console.Write(number % 2);

            Console.Write( number % 2 );

        return null;

    public static void Main( )
        Console.WriteLine("Enter a decimal number: ");
        uint number = uint.Parse( Console.ReadLine() );

        string result = Bin ( number );



1 solution

Bin always returns null, so result.PadLeft will always throw that Exception. And this isn't a task for recursion.

What are you trying to do? Write out the binary representation of a uint? If so, you could try result = System.Convert.ToString ( number , 2 ).PadLeft ( 32 , '0' )

If it's a homework assignment, then I think you ought to spend the weekend studying bitwise operations.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900