Bits Per Byte

  • Thread starter Thread starter William Stacey
  • Start date Start date
W

William Stacey

Put something like the following in your Global library and make em public
static or what ever you like:
You could also use sizeof(), but you need to use unsafe context for that, so
marshal works for this without needing unsafe.

int bitsInByte = Marshal.SizeOf(typeof(byte)) * 8;
int bitsInInt = Marshal.SizeOf(typeof(int)) * 8;
int bitsInLong = Marshal.SizeOf(typeof(long)) * 8;
Console.WriteLine("Bits in byte:"+bitsInByte);
Console.WriteLine("Bits in Int:"+bitsInInt);
Console.WriteLine("Bits in Long:"+bitsInLong);
 
Is there any constant in the .NET API Framework indicating the # of
bits per byte (or int, or anything else)? Kinda like
std::numeric_limits for C#? I know they're all constant (unlike C/C++)
I just have a built-in aversion to hardcoding 8 and 32 all over the
place in my code.

Thanks,
-ken
 
You can use sizeof to find the number of bytes for value
types.

I don't know of any predefined constant for the number of
bits in a byte (doesn't mean there isn't one), but
this'll work spendidly when placed in your source code:

private const int bitsInByte = 8;

DB connection strings and user names are one thing, but
it's ok to hardcode the color of the sun (yellow) or what
humans breath (air) or, for that matter, how many bits in
a byte (8 - It's not going to change).

If any of those things change, you're app likely will
have long since gone the way of the dinosaur.
 
I understand what you mean, but in both C# and the CLI, the byte datatype's
very definition is an 8-bit unsigned value. This is quite unlike the header
definitions in C/C++, which are allowed to change.
Considering the submission to standards, I doubt it will change. I have a
feeling it was part of the design to stop the tangle of type redefinition.
The only type I know that has a dynamic size in the framework is IntPtr,
which is defined to be platform-specific (in other words, 32-bit on 32-bit
systems, 64 bit on 64-bit systesm, etc.).

-Rob Teixeira [MVP]
 
Back
Top