Home > Enterprise >  R - Convert Integer to 8-bit binary
R - Convert Integer to 8-bit binary

Time:07-29

I have a 3 dimension array that represents RGB values from 0 to 255. I would like to convert each element of this array into an 8-bit binary value, including trailing/leading zeros.

I can use the inToBits() function to create a binary string using 32-bits, but I'm trying to have 8-bits only, with the format 0= '00000000' and 255= '11111111'

#2x2 array of RGB values
ints <- array(as.integer(c(1,100,255,143,10,12,14,55,15,84,31,96)), dim=c(2,2,3))

#Convert array into a binary string. Expect size of 2*2*3*32.
bit.32 <- paste0(as.character(intToBits(ints)),collapse = "")

My desired output would be: '1000000001001101111111111110001'...

CodePudding user response:

Like this ?

toBinary <- function(n){
  paste0(as.integer(rev(intToBits(n)[1:8])), collapse = "")
}

> toBinary(255)
[1] "11111111"
> toBinary(128)
[1] "10000000"
  •  Tags:  
  • r
  • Related