[R] Is there a way to force counters to be treated as "unsigned?"

Petr Savicky savicky at praha1.ff.cuni.cz
Tue Feb 15 21:28:24 CET 2011


On Mon, Feb 14, 2011 at 02:45:49PM -0800, David Wolfskill wrote:
> I am acquiring some sampled data that is time-stamped (with a
> POSIXct).  Some of the data is in the form of "counters" -- that
> is, what is interesting isn't value of a given counter at a given
> time, but the change in the counter from one sample to a later one.
> 
> As the counters are only incremented, they would be perceived to be
> monotonically increasing -- ideally.  Unfortunately, the counters can
> "wrap," with the effect being that a later value may appear to be
> smaller than an earlier one.
> 
> Other code I've seen (in C) that works with these counters merely casts
> the counters to (unsigned) before calculating the difference, then casts
> the result as (int).  Subject to the constraint that this trick only
> works if the system doing the calculation has the same size "int" as the
> target system, and assumes that negative numbers are represented in
> "twos-complement" form, it works well enough.
> 
> [E.g., suppose we are using 4-bit counters, 0 .. 15].  If a counter
> at T0 is (say) 14 and the value of the counter at T1 is (say) 3,
> the usual arithmetic would say that the difference is
> 
> 	3 - 14 => -11
> 
> But if we (instead) calculate
> 
> 	(int)((unsigned)3 - (unsigned)4) => 5
> 
> which works out to be correct.]
> 
> Is there a way to do something similar to this in R?

The arithmetic of unsigned integers between 0 and 2^k - 1 is the
same as the arithmetic mod 2^k. This suggests the following approach

  (3 - 14) %% 16

  [1] 5

Hope this helps.

Petr Savicky.



More information about the R-help mailing list