简体   繁体   中英

How can I get the bit width and sign of a type in C#?

I need to get data bit width of a type. How can I get that? For example how can I write a function as follows?

int x = 30;
Type t = x.GetType();
bool sign = IsSignedType(t); // int is signed type, so it's true
int width = GetWidth(t); // 32

For the size, you can use Marshal.SizeOf and multiply by the number of bits in a byte (hint: 8), though for the built-in value types it is probably easy enough and certainly faster to just use a case statement.

For the sign , I'd think bool sign = t == Math.Abs(t); would do.

EDIT:

To determine if it is a signed number, there is no built-in method, but there are only 3 5 of them:

public static class Application
{
    public enum SignedEnum : int
    {
        Foo,
        Boo,
        Zoo
    }

    public enum UnSignedEnum : uint
    {
        Foo,
        Boo,
        Zoo
    }

    public static void Main()
    {
        Console.WriteLine(Marshal.SizeOf(typeof(Int32)) * 8);
        Console.WriteLine(5.IsSigned());
        Console.WriteLine(((UInt32)5).IsSigned());
        Console.WriteLine((SignedEnum.Zoo).IsSigned());
        Console.WriteLine((UnSignedEnum.Zoo).IsSigned());

        Console.ReadLine();
    }
}

public static class NumberHelper
{
    public static Boolean IsSigned<T>(this T value) where T : struct
    {
        return value.GetType().IsSigned();
    }

    public static Boolean IsSigned(this Type t)
    {
        return !(
            t.Equals(typeof(Byte)) ||
            t.Equals(typeof(UIntPtr)) ||
            t.Equals(typeof(UInt16)) ||
            t.Equals(typeof(UInt32)) ||
            t.Equals(typeof(UInt64)) ||
            (t.IsEnum && !Enum.GetUnderlyingType(t).IsSigned())
            );
    }
}

@ChrisShain's answers the first part correctly. Assuming you can guarantee that t is a numeric type, to tell whether the type is signed or not you should be able to use expression trees to dynamically invoke the MaxValue const field on t , convert it to a bitarray and check to see if it uses the sign bit (or just use bitshift magic to test it without the conversion). I haven't done it this way but it should be doable. If you want an example, I can work through it.

Or do it the easy way with a switch statement (or series of if s) like everyone else does.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM