I have 8 bytes expressed as integer values stored in a list.

They correspond to a 64-bit counter with the lowest significant byte at first position.

Here is an example what I am doing:

byteIntegers = {123, 12, 0, 169, 255, 20, 67, 199};

counter=Total[Table[byteIntegers[[i]]*256^(i - 1), {i, 1, 8}]]

How would you calculate this value?


1 Answer 1


You can use

FromDigits[Reverse[byteIntegers], 256]

because the elements of the list can be considered digits of a number expressed in base 256.

If we did not have this function, we could also use

Total[byteIntegers 256^(Range@Length[byteIntegers] - 1)]

Whether you find this better than the Table version depends on taste.

  • $\begingroup$ I like your first solution more. $\endgroup$
    – mrz
    Feb 26, 2017 at 10:37
  • 1
    $\begingroup$ @mrz The second one is just showing what else you could do if the FromDigits function did not exist. This is how I would implement it. But your Table solution is more readable for those not used to the style of mine. You could change Total@Table[...] to Sum[...], which would be shorter, but personally I don't like that because I tend to think of Sum as a symbolic processing function. We could also do Total@MapIndexed[#1 256^(First[#2] - 1) &, byteIntegers], but it feels too convoluted to me. A similar solution can also be constructed with MapThread. $\endgroup$
    – Szabolcs
    Feb 26, 2017 at 11:27
  • 1
    $\begingroup$ @mrz Finally, we could also use Inner[#1 256^#2 &, byteIntegers, Range@Length[byteIntegers] - 1], which looks clever, but I need a second before I understand what it actually does. As usual, Mathematica has myriads of ways. The two ways I like the most (after FromDigits, which is the clear winner) are what you showed and my second solution. $\endgroup$
    – Szabolcs
    Feb 26, 2017 at 11:28
  • $\begingroup$ Thank you very much for your help and the additional solutions. $\endgroup$
    – mrz
    Feb 27, 2017 at 9:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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