programmer777 programmer777 - 25 days ago 11
R Question

R Conversion Hex to base64

I am trying to convert from hex to base64 but the conversion I get with functions like base64Encode or base64_enc do not match with the conversion I get from this site https://conv.darkbyte.ru/ or this site http://tomeko.net/online_tools/hex_to_base64.php?lang=en

library(RCurl)
library(jsonlite)

hex_number="9d0a5a7d6771dd7fa321a48a820f93627657df
3292548df1389533913a60328300a9cc80d982875a8d08bb7
602c59935cacae88ea635ed8d3cea9ef57b1884cc"

base64_enc(hex_number)
#"OWQwYTVhN2Q2NzcxZGQ3ZmEzMjFhNDhhODIwZjkzNjI3NjU3ZGYKMzI5M
#jU0OGRmMTM4OTUz\nMzkxM2E2MDMyODMwMGE5Y2M4MGQ5ODI4NzVhOGQwO
#GJiNwo2MDJjNTk5MzVjYWNhZTg4ZWE2\nMzVlZDhkM2NlYTllZjU3YjE4ODRjYw=="

base64Encode(hex_number)
#"OWQwYTVhN2Q2NzcxZGQ3ZmEzMjFhNDhhODIwZjkzNjI3NjU3ZGYKMzI5M
#jU0OGRmMTM4OTUzMzkxM2E2MDMyODMwMGE5Y2M4MGQ5ODI4NzVhOGQwOGJiNwo
#2MDJjNTk5MzVjYWNhZTg4ZWE2MzVlZDhkM2NlYTllZjU3YjE4ODRjYw=="

#desired result:
#nQpafWdx3X+jIaSKgg+TYnZX3zKSVI3xOJUzkTpgMoMAqcyA2YKHWo0Iu3YCxZk1ysrojqY17Y086p71exiEzA==


Also I have tried to chenge the HEX to text before changing it to HEX with the code in this page http://blog.entropic-data.com/2017/04/19/short-dealing-with-embedded-nul-in-string-manipulation-with-r/ I didn't get the result I want.

Answer Source

Borrow some code from the wkb package (or just install and use it directly) to convert the hex string into a raw vector before passing it to one of the base 64 conversion routines:

hex_number <- "9d0a5a7d6771dd7fa321a48a820f93627657df3292548df1389533913a60328300a9cc80d982875a8d08bb7602c59935cacae88ea635ed8d3cea9ef57b1884cc"

I'm "source-ing" this but you should copy the code locally if you plan on using it as GH could go down or the code could change.

source_url("https://raw.githubusercontent.com/ianmcook/wkb/master/R/hex2raw.R",
           sha1 = "4443c72fb3831e002359ad564f1f2a8ec5e45e0c")

openssl::base64_encode(hex2raw(hex_number))
## [1] "nQpafWdx3X+jIaSKgg+TYnZX3zKSVI3xOJUzkTpgMoMAqcyA2YKHWo0Iu3YCxZk1ysrojqY17Y086p71exiEzA=="

OR (if you are willing to have the wkb package as a dependency:

openssl::base64_encode(wkb::hex2raw(hex_number))