added gray encoding and decoding