This question may be useful: How to convert integer number into binary vector?
your_pixels <- c(0,1,100,255)
your_bits <- sapply(your_pixels, function(x) as.integer(intToBits(x)))
your_bits
[,1] [,2] [,3] [,4]
[1,] 0 1 0 1
[2,] 0 0 0 1
[3,] 0 0 1 1
[4,] 0 0 0 1
[5,] 0 0 0 1
[6,] 0 0 1 1
[7,] 0 0 1 1
[8,] 0 0 0 1
[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 # notice, no data here
[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
Then to get the value for your test #19, use your_bits[19,]
(unless you're counting 19 from the beginning of the number, in which case your_bits[14,]
). However, you will notice that the 19th bit for the entire range 0:255
will be 0. The highest bit used in the number 255 is the 8th bit.
The most common image encoding is usually RGBA, which is 32 bits per pixel (0:255 for each channel, red/blue/green/alpha). You mentioned your image has 48 bits per pixel. Integers in R are limited to 32 bits (and intToBits
only works on integers), so some detail about how you're reading the pixels into values would be necessary to help you.
There are packages to return the binary representation of large numbers, like bit64
: https://cran.r-project.org/web/packages/bit64/index.html
library(bit64)
your_pixels48 <- c(0, 1, 100, 255, 2^48-1)
[1] 0.00000e+00 1.00000e+00 1.00000e+02 2.55000e+02 2.81475e+14
your_pixels48 <- as.integer64(your_pixels48)
integer64
[1] 0 1 100 255 281474976710655
your_bits48 <- as.bitstring(your_pixels48)
[1] "0000000000000000000000000000000000000000000000000000000000000000"
[2] "0000000000000000000000000000000000000000000000000000000000000001"
[3] "0000000000000000000000000000000000000000000000000000000001100100"
[4] "0000000000000000000000000000000000000000000000000000000011111111"
[5] "0000000000000000111111111111111111111111111111111111111111111111"
However, note that this returns a string of the binary representation. In that case you can use string operations to access the 19th slot:
substr(your_bits48, start = 19, stop = 19)
[1] "0" "0" "0" "0" "1"
Which you then need to coerce to a number again with as.numeric
or as.integer
. However, this is counting from the beginning of the number, not the end, so you really need to start=
and stop=
at (64:1)[19]
or 46.
Presumably you want more data than just the 19th value, so you can also use strsplit(your_bits48, "")
to split the bitstring into every value, which can then be indexed in whatever way you want.