# Reading and re-assigning variable

I am trying to create a table by iteratively calculating its values using a temporary variable accu:

samplingRate = 500;
seconds = 0.2;
bits = 16;
maxV = 2.^bits;
freq = 500;
samples = samplingRate * seconds;
accu = 0;
inc = maxV *freq/samplingRate;
res = Table[
accu = accu + inc;
accu = BitAnd[accu, 255];
accu,
{t, 0, samples - 1}
];
ListPlot[res]
res


The line accu = accu + inc; is interpreted just the way I intended (it increments accu by inc. But in the next line, I expect Mathematica to take just the lowest 8 bits of accu and re-assign that value to accu. Instead, Mathematica seems to interpret this expression an equation that can be solved for accu: the first element of the Table is the unevaluated BitAnd function with its two arguments, the next entry is a nested combination of a BitAnd taking the first BitAnd as an argument etc. How can I force Mathematica to simply evaluate BitAnd and assign the result to accu (just like it does in the line above)?

• The problem is in your seconds = 0.2; and maxV = 2.^bits;; replace them with seconds = 1/5; and maxV = 2^bits; (or maxV = BitShiftLeft[1, bits]). Don't use inexact numbers with functions that expect integers like BitAnd[]. – J. M.'s ennui Nov 16 '19 at 12:10
• @J.M.willbebacksoon This answers my question. For the benefit of others who might read this, could you please post it as an answer so I can accept it? – travelboy Nov 16 '19 at 16:07

Since inc is 65536 and BaseForm[inc, 2] is 10000000000000000, accu will always be zero.

You can see this by observing the calculations

samplingRate = 500;
seconds = 1/5;
bits = 16;
maxV = 2^bits;
freq = 500;

samples = samplingRate seconds


100

inc = maxV freq/samplingRate


65536

BaseForm[inc, 2]


Then, of course,

BitAnd[inc, 255]


gives zero because the last four bits are all zero, and it follows that

accu = 0;
Table[accu = BitAnd[accu + inc, 255], samples] // Short


gives

{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, <<72>>, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}