8

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}
m_goldberg
  • 107,779
  • 16
  • 103
  • 257
bc888
  • 133
  • 4

4 Answers4

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

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

OkkesDulgerci
  • 10,716
  • 1
  • 19
  • 38
10

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} *)
Rohit Namjoshi
  • 10,212
  • 6
  • 16
  • 67
7

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₂}
J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
4
FlipBits[num_Integer, len_.] := 
 Module[{arr}, arr = IntegerDigits[num, 2, len];
  1 - arr]
bc888
  • 133
  • 4