Home > Back-end >  convert string to hexadecimal in R
convert string to hexadecimal in R

Time:03-08

I am trying to convert a string such as

 str <- 'KgHDRZ3N'

to hexadecimal. The function as.hexmode() returns an error

Error in as.hexmode("KgHDRZ3N") : 
  'x' cannot be coerced to class "hexmode"

are there any other functions I can use to achieve this?

I am trying to replicate what .encode() in python does.

CodePudding user response:

You can use charToRaw

charToRaw(str)
#> [1] 4b 67 48 44 52 5a 33 4e

Or if you want a character vector

as.hexmode(as.numeric(charToRaw(str)))
#> [1] "4b" "67" "48" "44" "52" "5a" "33" "4e"

or if you want the "0x" prefix:

paste0("0x", as.hexmode(as.numeric(charToRaw(str))))
#> [1] "0x4b" "0x67" "0x48" "0x44" "0x52" "0x5a" "0x33" "0x4e"
  • Related