在R中将十进制转换为二进制? [英] Converting decimal to binary in R?
问题描述
在 R 中将数字转换为基数 2(在字符串中,例如 5 将转换为 "0000000000000101"
)的最简单方法是什么?有 intToBits
,但它返回一个字符串向量而不是一个字符串:
What would be the easiest way to convert a number to base 2 (in a string, as for example 5 would be converted to "0000000000000101"
) in R? There is intToBits
, but it returns a vector of strings rather than a string:
> intToBits(12)
[1] 00 00 01 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[26] 00 00 00 00 00 00 00
我尝试了一些其他功能,但没有成功:
I have tried some other functions, but had no success:
> toString(intToBits(12))
[1] "00, 00, 01, 01, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00"
推荐答案
请注意 intToBits()
返回原始"向量,而不是字符向量(字符串).请注意,我的答案是 @nico 的原始答案 的轻微扩展,它从每个位中删除了前导0":>
Note that intToBits()
returns a 'raw' vector, not a character vector (strings). Note that my answer is a slight extension of @nico's original answer that removes the leading "0" from each bit:
paste(sapply(strsplit(paste(rev(intToBits(12))),""),`[[`,2),collapse="")
[1] "00000000000000000000000000001100"
为了清楚起见,分解步骤:
To break down the steps, for clarity:
# bit pattern for the 32-bit integer '12'
x <- intToBits(12)
# reverse so smallest bit is first (little endian)
x <- rev(x)
# convert to character
x <- as.character(x)
# Extract only the second element (remove leading "0" from each bit)
x <- sapply(strsplit(x, "", fixed = TRUE), `[`, 2)
# Concatenate all bits into one string
x <- paste(x, collapse = "")
x
# [1] "00000000000000000000000000001100"
或者,如 @nico 所示,我们可以使用 as.integer()
作为从每个位中删除前导零的更简洁的方法.
Or, as @nico showed, we can use as.integer()
as a more concise way to remove the leading zero from each bit.
x <- rev(intToBits(12))
x <- paste(as.integer(x), collapse = "")
# [1] "00000000000000000000000000001100"
为了方便复制粘贴,这里是上面的函数版本:
Just for copy-paste convenience, here's a function version of the above:
dec2bin <- function(x) paste(as.integer(rev(intToBits(x))), collapse = "")
这篇关于在R中将十进制转换为二进制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!