Bit flip only function?

Torbjörn Granlund tg at gmplib.org
Mon Jul 21 11:49:34 UTC 2014


Viktor Kletzhändler <vkletzhaendler at swissonline.ch> writes:

  That would mean, mpz_com assumes that all numbers are signed two's
  complement representations. Therefore it silently adds a sign bit to
  any positive argument, and calculates the two's complement for any
  negative argument.
  
  This is ok. However, that would also mean that mpz_com can't take
  unsigned arguments, i.e. a bit string without embedded sign, for
  example (unsigned int) 175. Or am I missing something again?
  
Don't think in "types", think maths.  The number 175 can be represented
by mpz (sic!).  If you negate it, you'll get -175, if you apply ~ (alias
mpz_com) you'll get -176.  It is completely well-defined, and will not
be affected by some host word sizes or the sizes of this or that type of
your C compiler.  (You might notice that - and ~ applied to "unsigned"
integral types in C will yield different values depending on the word
size; except for that quirk they are well-defined.)

>From your reasoning I suspect that you shouldn't be using GMP at all, or
at least not the mpz functions.  Handling "bit strings" is easy enough
to do with a few discrete C functions.  But if your bit strings are very
large, you may get some benefit from using mpn_ logic functions; you
might be relieved to know that they handle any number of 'words' (aka
limbs) without mpz's implied infinite left extensions of ones or zeros.


Torbjörn
Please encrypt, key id 0xC8601622


More information about the gmp-discuss mailing list