Path: csiph.com!eternal-september.org!feeder.eternal-september.org!reader01.eternal-september.org!.POSTED!not-for-mail From: Tim Rentsch Newsgroups: comp.lang.c++ Subject: Re: two's complement idea Date: Sat, 15 Feb 2020 05:56:02 -0800 Organization: A noiseless patient Spider Lines: 30 Message-ID: <86a75kgdjh.fsf@linuxsc.com> References: <868slti7gm.fsf@linuxsc.com> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: reader02.eternal-september.org; posting-host="9b44be6d216a534b4907eb1c17f8f0ca"; logging-data="10085"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+rW+bBsuaQHLXiJUx1XwOFifLSCl6Ax+E=" User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux) Cancel-Lock: sha1:D7BLWeYTGv68B6p2/WsHNEbhw4Y= sha1:IyRsm7f05LHT5gTtng8pXfjSpa4= Xref: csiph.com comp.lang.c++:71855 "Alf P. Steinbach" writes: > On 27.01.2020 10:17, Tim Rentsch wrote: > >> "Alf P. Steinbach" writes: >> >>> On 22.01.2020 08:32, Bonita Montero wrote: >>> >>>> I recently had the problem that I wanted to have a constant which is >>>> size_t wide and where the highest bit is set. I simply solved it that >>>> way (I assume ptrdiff_t as wide as size_t, but this should be common >>>> today on all platforms): >>>> std::size_t const SIZE_T_MSB = std::numeric_limits::min(); >>>> A guarantee from the standard that signed values are 2's-complement >>>> woud be nice for that. >>> >>> C++20 will give you that guarantee. >>> >>> But e.g. `size_t(-1) - size_t(-1)/2` does the job with just C++98 >>> guarantees. >> >> Or just size_t(-1)/2+1. > > Or ~(size_t(-1)/2). In practice that is highly likely to work, but strictly speaking it is not guaranteed (at least not in C; I believe that holds also in C++ but I am less well-versed in the C++ standard than the C standard). The reason is size_t is not required to be at least as wide as int, so the ~ could produce a negative value.