# BitNot does not flip bits in the way I expected

Can anyone explain why the last result in these statements is not the bit-flipped version of arr?

(Debug) In[189]:= arr = {0, 0, 1, 0, 0, 0, 1, 0}

(Debug) Out[189]= {0, 0, 1, 0, 0, 0, 1, 0}

(Debug) In[190]:= FromDigits[%, 2]

(Debug) Out[190]= 34

(Debug) In[191]:= BitNot[%]

(Debug) Out[191]= -35

(Debug) In[192]:= IntegerDigits[%, 2, 8]

(Debug) Out[192]= {0, 0, 1, 0, 0, 0, 1, 1}

• "IntegerDigits[n] discards the sign of n." – kglr Mar 12 at 21:37
• Is there a work around? – bc888 Mar 12 at 21:43
• not any I know of. – kglr Mar 12 at 21:44
• Integers can have arbitrary length, so how many leading zeros should be flipped? The documentation clarifies: "Integers are assumed to be represented in two's complement form, with an unlimited number of digits, so that BitNot[n] is simply equivalent to -1-n." – Chip Hurst Mar 12 at 22:00
• If you just want to flip "bits" in an array of 1/0 elements without the need to go between integer representation, just use BitXor[1,array]... – ciao Mar 14 at 6:34

I don't think there is a built-in function to generate the two's complement representation. Easy to implement though.

twosComplement[x_, n_] := IntegerDigits[2^x - n, 2, n]
twosComplement[35, 8]
(* {1, 1, 0, 1, 1, 1, 0, 1} *)

twosComplement[x_, n_] := UnitBox@IntegerDigits[x, 2, n]
twosComplement[35, 8]


{1, 1, 0, 1, 1, 1, 0, 1}

Without using IntegerDigits[]:

With[{n = 34},
{n, BitXor[BitShiftLeft[1, BitLength[n]] - 1, n]} // BaseForm[#, 2] &]
{100010₂, 11101₂}

With[{n = 34, p = 8},
{n, BitXor[BitShiftLeft[1, p] - 1, n]} // BaseForm[#, 2] &]
{100010₂, 11011101₂}

FlipBits[num_Integer, len_.] :=
Module[{arr}, arr = IntegerDigits[num, 2, len];
1 - arr]