简体   繁体   中英

convert string to hexadecimal in R

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.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM