Search code examples
rgray-code

Convert Gray Code to Decimal in R


I have a set of 0's and 1's represented as a list initially created with sample(c(0,1), n, replace=TRUE), where n is the length of my binary number. I'm currently using a BCD converter to convert my binary number to a decimal number, this is seen here:

BCD.to.Decimal <- function(binaryNumb)
{
  binaryLength = length(binaryNumb)
  decimalNumb = 0
  for(i in 1:binaryLength)
  {
    if ( binaryNumb[i] == 1)
      decimalNumb = decimalNumb + 2^(binaryLength - i)
 }

  decimalNumb
}

I would like to instead use a GrayCode.To.Decimal converter which does the same job as my BCD.to.Decimal converter, but using Gray Code instead.

Note: Speed DOES matter for this, and I would like to do this in the most efficient way possible. I'm aware that my BCD converter is probably not the most efficient, its just the simplest, if you have a significantly more efficient way of handling BCD conversion I'd also be interested in hearing about that.

What is Gray Code?: http://en.wikipedia.org/wiki/Gray_code


Solution

  • Here is the simple solution to my question, the algorithm ended up being much easier than it first appeared. The algorithm used can be found here.

    GrayCode.to.Decimal <- function(grayNumb)
    {
      binaryNumb = vector("numeric",length(grayNumb))
      binaryNumb[1] = grayNumb[1]
      for (i in 2:length(grayNumb))
      {
        binaryNumb[i] = xor(grayNumb[i], binaryNumb[i - 1])
      }
    
      return(Binary.to.Decimal(binaryNumb))
    }
    

    This code will convert the code into binary where you can then use a binary conversion to convert it to a decimal number. I'm choosing to use the code provided by flodel in the comments section.

    Binary.to.Decimal <- function(binaryNumb)
    {
      L = length(binaryNumb)
      sum(2L^(seq_along(binaryNumb)-1L) * rev(binaryNumb))
    }