如何使用R將整數轉換爲二進制向量?如何將整數轉換爲二進制向量?
例如:
number <- 11
[1] 1 0 1 1
什麼是轉換的可能的最快方法(,使用R代碼或從包一些現有的函數),如果我需要數的整個矢量(最小值轉換= 0,最大= 300)變成二元矩陣?
如何使用R將整數轉換爲二進制向量?如何將整數轉換爲二進制向量?
例如:
number <- 11
[1] 1 0 1 1
什麼是轉換的可能的最快方法(,使用R代碼或從包一些現有的函數),如果我需要數的整個矢量(最小值轉換= 0,最大= 300)變成二元矩陣?
還有的intToBits
功能轉換爲32和原糖的向量的任何一個數字,所以你可以這樣做:
decimals <- c(3,5,11,4)
m <- sapply(decimals,function(x){ as.integer(intToBits(x))})
m
> m
[,1] [,2] [,3] [,4]
[1,] 1 1 1 0
[2,] 1 0 1 0
[3,] 0 1 0 1
[4,] 0 0 1 0
[5,] 0 0 0 0
[6,] 0 0 0 0
[7,] 0 0 0 0
[8,] 0 0 0 0
[9,] 0 0 0 0
[10,] 0 0 0 0
[11,] 0 0 0 0
[12,] 0 0 0 0
[13,] 0 0 0 0
[14,] 0 0 0 0
[15,] 0 0 0 0
[16,] 0 0 0 0
[17,] 0 0 0 0
[18,] 0 0 0 0
[19,] 0 0 0 0
[20,] 0 0 0 0
[21,] 0 0 0 0
[22,] 0 0 0 0
[23,] 0 0 0 0
[24,] 0 0 0 0
[25,] 0 0 0 0
[26,] 0 0 0 0
[27,] 0 0 0 0
[28,] 0 0 0 0
[29,] 0 0 0 0
[30,] 0 0 0 0
[31,] 0 0 0 0
[32,] 0 0 0 0
這個SO post建議intToBits
功能。我定義了函數number2binary
,其中包含一個參數noBits
來控制返回多少位。標準是返回32位。
number2binary = function(number, noBits) {
binary_vector = rev(as.numeric(intToBits(number)))
if(missing(noBits)) {
return(binary_vector)
} else {
binary_vector[-(1:(length(binary_vector) - noBits))]
}
}
而對於一些例子:
> number2binary(11)
[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 1
> number2binary(11, 4)
[1] 1 0 1 1
我得到'長度(number2binary(0,32))== 31' ......? –
你可以使用以下功能爲基礎,intToBit
:
intToBitVect <- function(x){
tmp <- rev(as.numeric(intToBits(x)))
id <- seq_len(match(1,tmp,length(tmp))-1)
tmp[-id]
}
第一行將intToBits輸出轉換爲數字0和1,並將訂單放置正確。第二行檢查需要保留哪些值,如下所示:
match
檢查第一個出現的位置。如果找不到1,請詢問match
以返回tmp
向量的長度。tmp
矢量先前到的1
第一次出現的位置tmp
向量中的所有那些位置要顯示它的工作原理:
> intToBitVect(11)
[1] 1 0 1 1
> intToBitVect(0)
[1] 0
我已經在「將R書」 MJ克拉雷發現一種解決方案是下列的函數:
binary <- function(x) {
i <- 0
string <- numeric(32)
while(x > 0) {
string[32 - i] <- x %% 2
x <- x %/% 2
i <- i + 1
}
first <- match(1, string)
string[first:32]
}
這個功能很棒!這是迄今爲止最一般的解決方案..榮譽!! –
如果你想返回一個二進制序列,即1和0的向量,那麼這個函數會爲你做,但一次只能取1個數字。
dectobin <- function(y) {
# find the binary sequence corresponding to the decimal number 'y'
stopifnot(length(y) == 1, mode(y) == 'numeric')
q1 <- (y/2) %/% 1
r <- y - q1 * 2
res = c(r)
while (q1 >= 1) {
q2 <- (q1/2) %/% 1
r <- q1 - q2 * 2
q1 <- q2
res = c(r, res)
}
return(res)
}
而另:
toBits <- function (x, nBits = 8){
tail(rev(as.numeric(intToBits(x))),nBits)
}
intToBin <- function(x){
if (x == 1)
1
else if (x == 0)
NULL
else {
mod <- x %% 2
c(intToBin((x-mod) %/% 2), mod)
}
}
所以intToBin(10)返回
[1] "1" "0" "1" "0"
如果你想字符串,而不是矢量
> paste0(intToBin(10), collapse = "")
[1] "1010"
嘗試CRAN包 「binaryLogic」
library(binaryLogic)
as.binary(11)
[1] 1 0 1 1
as.binary(11, littleEndian=TRUE)
[1] 1 1 0 1
as.binary(42, n=16)
[1] 0 0 0 0 0 0 0 0 0 0 1 0 1 0 1 0
as.binary(0:2, n=2)
[[1]]
[1] 0 0
[[2]]
[1] 0 1
[[3]]
[1] 1 0
as.binary(0xFF)
[1] 1 1 1 1 1 1 1 1
還有:平移,旋轉,格雷碼等
不應該第3行是1011? – nikpod
@nikpod你想要第三列的相反,這是'0000 ... 00001011' – digEmAll
我的壞,是看着它明智的行。數字5和4巧合地表示在行中 – nikpod