Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strtoul of negative number

Tags:

c++

c

string

The following C++ program calls strtoul of negative 1. Since no negative numbers are representable in any unsigned type, I had expected this to fail and return 0

If no valid conversion could be performed, a zero value is returned.

but instead a large positive number is returned

If the value read is out of the range of representable values by an unsigned long int, the function returns ULONG_MAX (defined in <climits>), and errno is set to ERANGE.

#include <cstdlib>
#include <iostream>

int main () {
  {char s[] = "-1";
    for (int b=0; b<17; ++b)
      std::cout << "strtoul (unsigned) of " << s
                << " with base arg " << b
                << ": " << strtoul(s,0,b) << std::endl;}
}

Why does strtoul not fail and return 0 for negative numbers?

like image 772
hkBst Avatar asked Jun 07 '16 14:06

hkBst


People also ask

Does Strtol work with negative numbers?

If the value is negative, the strtol() function will return LONG_MIN, and the strtoll() function will return LONGLONG_MIN. If no characters are converted, the strtoll() and strtol() functions will set errno to EINVAL and 0 is returned.

What is the value of a negative number?

A negative number is a number whose value is always less than zero and it has a minus (-) sign before it. On a number line, negative numbers are represented on the left side of zero. For example, -6 and -15 are negative numbers.

How do you code a negative number?

Negative Numbers The simplest is to simply use the leftmost digit of the number as a special value to represent the sign of the number: 0 = positive, 1 = negative. For example, a value of positive 12 (decimal) would be written as 01100 in binary, but negative 12 (decimal) would be written as 11100.

What is negative number give example?

Negative numbers can be thought of as resulting from the subtraction of a larger number from a smaller. For example, negative three is the result of subtracting three from zero: 0 − 3 = −3.


1 Answers

You better use cppreference.com for documentation it seems to be much more accurate:

if the minus sign was part of the input sequence, the numeric value calculated from the sequence of digits is negated as if by unary minus in the result type, which applies unsigned integer wraparound rules.

and as mentioned there optional plus or minus sign is a valid symbol

like image 150
Slava Avatar answered Oct 03 '22 03:10

Slava