Friday, June 3, 2016

How do you convert from Hexadecimal to decimal and decimal to hexadecimal in R?


In R programming, Integer creates an integer vector
as.integer coerces(forces) its argument to integer type

This information is from R documentation:

Character strings containing optional whitespace followed by either a decimal representation or a hexadecimal representation (starting with 0x or 0X) can be converted, as well as any allowed by the platform for real number

Hexadecimal to Decimal Conversion:

Let us take a decimal number 78 and its hexadecimal value is 4E (or 4e)

This is how you code it in R. You have to use the string representation by appending 0x. Note that the function is case sensitive.
---
> as.integer("0x4E")
[1] 78
---

Decimal to Hexadecimal Conversion:

You need to use the sprintf(fmt,...) function as in converting the decimal 78 to hexadecimal. sprintf() is a wrapper for the C-library function.
-----
 > sprintf("%x",78)
[1] "4e"

or

> sprintf("%X",78)

[1] "4E"
-----

No comments: