Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unsigned versus signed numbers as indexes

Whats the rationale for using signed numbers as indexes in .Net?

In Python, you can index from the end of an array by sending negative numbers, but this is not the case in .Net. It's not easy for .Net to add such a feature later as it could break other code perhaps using special rules (yeah, a bad idea, but I guess it happens) on indexing.

Not that I have ever have needed to index arrays over 2,147,483,647 in size, but I really cannot understand why they choose signed numbers.

Can it be because it's more normal to use signed numbers in code?

Edit: I just found these links:

The perils of unsigned iteration in C/C++

Signed word lengths and indexes

Edit2: Ok, a couple of other good reasons from the thread Matthew Flaschen posted:

  • Historical reasons as it's a c-like language
  • Interop with c
like image 874
simendsjo Avatar asked Jun 17 '10 08:06

simendsjo


People also ask

What is the difference between unsigned and signed numbers?

A signed integer is a 32-bit datum that encodes an integer in the range [-2147483648 to 2147483647]. An unsigned integer is a 32-bit datum that encodes a nonnegative integer in the range [0 to 4294967295].

How do you know if its signed or unsigned?

An unsigned number contains just zero or positive values, whereas a signed number has both positive and negative numbers along with the value zero. The maximum value of signed numbers is half that of unsigned numbers.

Should you use unsigned integers?

Unsigned integers are used when we know that the value that we are storing will always be non-negative (zero or positive). Note: it is almost always the case that you could use a regular integer variable in place of an unsigned integer.

Can signed integers represent more values than unsigned integers?

Both can store 256 different values, but signed integers use half of their range for negative numbers, whereas unsigned integers can store positive numbers that are twice as large. An n-bit unsigned variable has a range of 0 to (2n)-1.


3 Answers

It may be to the long tradition of using a value below 0 as an invalid index. Methods like String.IndexOf return -1 if the element is not found. Therefore, the return value must be signed. If index-consumers would require unsigned values, you would have to a) check and b) cast the value to use it. With signed indices, you just need the check.

like image 126
Arne Avatar answered Oct 16 '22 06:10

Arne


For simplicity of course. Do you like trouble doing size arithmetic with unsigned ints?

like image 39
Rotsor Avatar answered Oct 16 '22 05:10

Rotsor


Unsigned isn't CLS compliant.

like image 27
Hans Olsson Avatar answered Oct 16 '22 07:10

Hans Olsson