Home > other >  In R decoding binary to decimal
In R decoding binary to decimal

Time:01-26

It is from this article, pg 202:

https://journal.r-project.org/archive/2017/RJ-2017-008/RJ-2017-008.pdf, it is in the Genetic Algorithm package

library(GA)
decode <- function(string, bitOrders)
{
string <- split(string,  rep.int(seq.int(bitOrders), times = bitOrders))
orders <- sapply(string, function(x) { binary2decimal(gray2binary(x)) })
return(unname(orders))
}

I do not understand why the first line gives (3,1,1) and the second line gives (2,1,1), shouldn‘t it be the other way round?

decode(c(0,1,0, 0,1, 0,0,1), bitOrders =   c(3,2,3))
[1] 3 1 1


decode(c(0,1,1, 0,1, 0,0,1), bitOrders =   c(3,2,3))
[1] 2 1 1

CodePudding user response:

This function doesn't convert binary to decimal, it converts Grey Encoded binary to decimal.

Note that the decode() function assumes that the input binary string is expressed using Gray encoding, which ensures that consecutive values have the same Hamming distance (Hamming, 1950).

If we look at the code, the vector is split, then run through gray2binary(), then binary2decimal(). I haven't heard of it before, but it's aparantly a different version of binary encoding where increasing the number by 1 only involves changing a single number. Well, what is Grey encoding? From the ?gray2binary help:

Gray encoding allows to obtain binary strings not affected by the well-known Hamming cliff problem. With Gray encoding the number of bit differences between any two consecutive values is one, whereas in binary strings this is not always true.

# Consider a five-bit encoding of values 15 and 16  using the standard 
# binary coding

decimal2binary(15, 5)
[1] 0 1 1 1 1
decimal2binary(16, 5)
[1] 1 0 0 0 0

# Moving from 15 to 16 (or vice versa) all five bits need to be changed,
# but using Gray encoding the two binary strings differ by one bit.

binary2gray(decimal2binary(15, 5))
[1] 0 1 0 0 0
binary2gray(decimal2binary(16, 5))
[1] 1 1 0 0 0

We can use a simple loop to see how 1:10 looks in binary vs grey encoding

# Grey encoding
sapply(1:10, function(x) paste(binary2gray(decimal2binary(x)), collapse = ''))
 [1] "1"    "11"   "10"   "110"  "111"  "101"  "100"  "1100" "1101" "1111"

# Binary
sapply(1:10, function(x) paste(decimal2binary(x), collapse = ''))
 [1] "1"    "10"   "11"   "100"  "101"  "110"  "111"  "1000" "1001" "1010"

  •  Tags:  
  • Related