intT-6ren">
gpt4 book ai didi

r - 在R中将十进制转换为二进制?

转载 作者:行者123 更新时间:2023-12-03 07:53:53 25 4
gpt4 key购买 nike

在 R 中将数字转换为基数 2(在字符串中,例如 5 将转换为 "0000000000000101")的最简单方法是什么?有intToBits ,但它返回一个字符串向量而不是一个字符串:

> 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

我尝试了一些其他功能,但没有成功:
> 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's original answer 的轻微扩展从每个位中删除前导“0”:

paste(sapply(strsplit(paste(rev(intToBits(12))),""),`[[`,2),collapse="")
[1] "00000000000000000000000000001100"

为了清楚起见,分解步骤:
# 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 showed ,我们可以使用 as.integer()作为从每个位中删除前导零的更简洁的方法。
x <- rev(intToBits(12))
x <- paste(as.integer(x), collapse = "")
# [1] "00000000000000000000000000001100"

只是为了方便复制粘贴,这里有一个上面的函数版本:
dec2bin <- function(x) paste(as.integer(rev(intToBits(x))), collapse = "")

关于r - 在R中将十进制转换为二进制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6614283/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com