[英]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. 对于大小,您可以使用Marshal.SizeOf并乘以字节的位数(提示:8),尽管对于内置值类型来说,仅使用case语句可能很容易,而且肯定更快。
For the sign , I'd think bool sign = t == Math.Abs(t);
对于符号,我认为
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: 3
其中5个:
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. @ChrisShain正确回答了第一部分。 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). 假设您可以保证
t
是数字类型,则可以使用表达式树来动态调用t
上的MaxValue
const字段,将其转换为位数组,并检查是否使用符号位(或仅使用位移位魔术来测试它而不进行转换)。 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. 或者像其他所有人一样,使用
switch
语句(或一系列if
)以简单的方式进行操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.