7
$\begingroup$

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}
$\endgroup$
  • 5
    $\begingroup$ "IntegerDigits[n] discards the sign of n." $\endgroup$ – kglr Mar 12 '19 at 21:37
  • $\begingroup$ Is there a work around? $\endgroup$ – bc888 Mar 12 '19 at 21:43
  • $\begingroup$ not any I know of. $\endgroup$ – kglr Mar 12 '19 at 21:44
  • 10
    $\begingroup$ 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." $\endgroup$ – Chip Hurst Mar 12 '19 at 22:00
  • 1
    $\begingroup$ 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]... $\endgroup$ – ciao Mar 14 '19 at 6:34
9
$\begingroup$

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} *)
| improve this answer | |
$\endgroup$
10
$\begingroup$
twosComplement[x_, n_] := UnitBox@IntegerDigits[x, 2, n]
twosComplement[35, 8]

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

| improve this answer | |
$\endgroup$
6
$\begingroup$

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₂}
| improve this answer | |
$\endgroup$
4
$\begingroup$
FlipBits[num_Integer, len_.] := 
 Module[{arr}, arr = IntegerDigits[num, 2, len];
  1 - arr]
| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.