tags:

views:

260

answers:

2

What is the difference between a word and ushort in C#? They are both 16 bits!

+7  A: 

C# does not have a word type. If you mean short or Int16, the difference is that ushort is unsigned.

short can be any value from -32768 to 32767, whereas ushort can be from 0 to 65535. They have the same total range and use the same number of bits but are interpreted in different ways, and have different maximums/minimums.

Clarification: A word is a general computer science term that is typically used to refer to the largest single group of bits that can be handled by the CPU in a single operation. So if your CPU (and operating system) are 32-bit, then a word is an Int32 or UInt32 (C#: int/uint). If you're on a 64-bit CPU/OS, a word is actually an Int64/UInt64 (C#: long/ulong). The term "word" usually refers only to the bit size of a variable as opposed to how it is actually interpreted in a program.

Aaronaught
Ah thanks, I guess the lesson I was reading was just talking about it conceptually and I understood that there actually is a word type!
Adam
In addition, a language can have more than one name for a type. For instance, in C, an `int`, a `long`, and an `int32_t` are the same in some implementations.
Zarel
@Adam: I added in a clarification which I think might help. "Word" refers to a fixed-size group of bits; however, there may be many different ways that this word can be interpreted, each of which forms a type in a language (such as `int` or `uint`).
Aaronaught
@Zarel: Yes, exactly. IIRC, C++ and C typically typedef `WORD` as `unsigned int`, so in that case it is equivalent to the C# `uint`. However, there are no such typedefs in C#, you have to explicitly specify `[u]short/int/long` and these are all aliases for the CLR structs `[U]Int16/Int32/Int64`.
Aaronaught
No, WORD is 16 bits. The first version of Windows ran on 16-bit CPUs.
Hans Passant
@nobugz: You're right, `WORD` is `unsigned short` in windef.h, that was a mistake in my comment above. It can still vary significantly by platform, though, and does not exist in C#, so I think that the concept of a machine word is the most important thing here; if someone decides to start programming in Windows C++ then they will quickly pick up the subtle differences, such as the `WORD` type being fixed to 16-bits for backward compatibility.
Aaronaught
A: 

A (machine) word is the native size of the processor registers. It's generally what C has used as size for the int data type. In C# the data types has a fixed size and does not depend on the processor architecture.

In Intel assembly language the WORD data type has come to mean 16 bits, a DWORD (double word) is 32 bits and a QWORD (quad word) is 64 bits. The WORD type is also used in the Windows API with the same meaning.

So, the WORD data type corresponds to the C# type ushort.

Guffa