进制转换

基本类型 / 数字 / 整型

# 十六进制计数法
hexadecimal <- 0x42
# hexadecimal = 66

# 陷阱:没有八进制字面量,042 就是普通的十进制数
octal_literal <- 042
# octal_literal = 42

# 八进制和二进制要从字符串转换
octal <- strtoi("42", base = 8L)
# octal = 34
binary <- strtoi("1010", base = 2L)
# binary = 10

# 42 转八进制字符串
s_octal <- sprintf("%o", 42L)
# s_octal = 52

# 42 转十六进制字符串
s_hexadecimal <- sprintf("%x", 42L)
# s_hexadecimal = 2a

# 42 转二进制字符串:32 位,去掉前导 0
bits <- rev(as.integer(intToBits(42L)))
s_binary <- sub("^0+", "",
                paste(bits, collapse = ""))
# s_binary = 101010

# 任意进制的字符串转回 int
from_hexadecimal <- strtoi("2a", base = 16L)
# from_hexadecimal = 42

cat("hexadecimal =", hexadecimal, "\n")
cat("octal_literal =", octal_literal, "\n")
cat("octal =", octal, "\n")
cat("binary =", binary, "\n")
cat("s_octal =", s_octal, "\n")
cat("s_hexadecimal =", s_hexadecimal, "\n")
cat("s_binary =", s_binary, "\n")
cat("from_hexadecimal =", from_hexadecimal, "\n")