How to portably convert a string into an uncommon integer type?

前端 未结 3 888
臣服心动
臣服心动 2020-12-30 07:46

Some background: If I wanted to use for, for instance, scanf() to convert a string into a standard integer type, like uint16_t, I’d use SCNu1

3条回答
  •  死守一世寂寞
    2020-12-30 08:16

    It depends on exactly how portable you want to be. POSIX says that pid_t is a signed integer type used to store process IDs and process group IDs. In practice, you could assume with safety that long is big enough. Failing that, your intmax_t must be big enough (so it will accept any valid pid_t); the trouble is, that type could accept values that are not legitimate in pid_t. You're stuck between a rock and a hard place.

    I would use long and not worry very much about it except for an obscure comment somewhere that a software archaeologist of 100 years hence will find and observe gives a reason why the 256-bit CPU is creaking to a halt when handed a 512-bit value as a pid_t.

    POSIX 1003.1-2008 is now available on the web (all 3872 pages of it, in PDF and HTML). You have to register (free). I got to it from the Open Group Bookstore.

    All that I see there is that it must be a signed integer type. Clearly, all valid signed integer values fit into intmax_t. I cannot find any information in or that indicates PID_T_MAX or PID_T_MIN or other such values (but I've only just this evening got access to it, so it could be hidden where I haven't looked for it). OTOH, I stand by my original comment - I believe that 32-bit values are pragmatically adequate, and I would use long anyway, which would be 64-bit on 8-bit machines. I suppose that roughly the worst thing that could happen is that an 'appropriately privileged' process read a value that was too large, and sent a signal to the wrong process because of a mismatch of types. I'm not convinced I'd be worried about that.

    ...oooh!...p400 under

    The implementation shall support one or more programming environments in which the widths of blksize_t, pid_t, size_t, ssize_t, and suseconds_t are no greater than the width of type long.

提交回复
热议问题