How to convert hexadecimal to binary in a matrix in r?

Asked

Viewed 145 times

0

I have a matrix with hexadecimal number, so:

     [,1] [,2] [,3]
[1,] "FA" "F8" "D0"
[2,] "CE" "17" "6A"
[3,] "0E" "D6" "22"

If I try to convert into binary, with hex2bin(matriz) (biblioteca BMS), is given to me:

  [1] 1 1 1 1 1 0 1 0 0 0 0 0 1 1 0 0 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 1 0 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0
 [62] 0 0 1 0 1 1 1 0 0 0 0 1 1 0 1 0 1 1 0 0 0 0 0 0 1 1 0 0 0 1 0 0 0 0 0 1 1 0 1 0 0 0 0 0 0 0 0 0 1 1 0 1 0 1 0 0 0 0 0 0 0
[123] 1 0 0 0 1 0 0 0 0 0 1 1 1 1 1 0 1 0 0 0 0 0 1 0 0 1 0 1 1 0 0 0 0 0 0 1 1 1 1 1 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0
[184] 1 0 0 0 1

But you need a matrix.

1 answer

1


The following function may do what you want.
First the data.

m <- matrix(c("FA", "F8", "D0", "CE", "17", "6A", "0E", "D6", "22"),
            nrow = 3, byrow = TRUE)

Now the code.

library(BMS)

hex2matrix <- function(M){
  R <- NULL
  for(i in seq_len(ncol(M))){
    B <- sapply(M[, i], hex2bin)
    R <- cbind(R, B)
  }
  R
}


hex2matrix(m)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.