Haribo
Haribo

Reputation: 2226

Matlab function uint8 in R

How I could generate a uint8 object in R with similar characterization that I could get from uint8 function in Matlab ? I have tried this github link, but the result is different. For example :

R :
b02 <- as.uint8(  2)
b0a <- as.uint8( 10)
bff <- as.uint8(255)

bff + b0a
[1] 9
bff/b0a
[1] 25
b02 ^ b0a
[1] 0

is.numeric(bff)
[1] FALSE
> class(bff)
[1] "uint8"

str(b02)
 'uint8' raw 02
str(b02)
 'uint8' raw 02
str(bff)
 'uint8' raw ff

Matlab :

b02=uint8(  2)
b02 =
  uint8
   2
>> b0a =uint8( 10)
b0a =
  uint8
   10
>> bff =uint8(255)
bff =
  uint8
   255

bff + b0a
ans =
  uint8
   255
bff/b0a
ans =
  uint8
   26
b02 ^ b0a 
ans =
  uint8
   255
isnumeric(bff)
ans =
  logical
   1
>> strcmp(class(bff),'uint8')
ans =
  logical
   1

class(b02)
ans =
    'uint8'
>> class(b0a)
ans =
    'uint8'
>> class(bff)
ans =
    'uint8'

Upvotes: 0

Views: 221

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173878

It seems unlikely that solving the problem as stated is going to help you towards your ultimate goal. In R the closest thing to a uint8 is raw format. This can be converted to any other data type you choose, so it is best to learn to work with it.

For completeness, it is worth pointing out that with R's S3 object-oriented system it is very easy to define your own uint8 class. Here's an extremely simplified example, which can take numeric or raw data and performs simple arithmetic as expected.

uint8 <- function(x)
{
  if(class(x) == "uint8") x <- unclass(x)
  if(is.raw(x)) x <- as.integer(x)
  if(is.numeric(x)) x <- as.integer(x)
  if(!is.integer(x)) stop("uint8 only takes numeric or raw types")

  if(any(x >= 256 | x < 0)) stop("uint8 numbers must be between 0 and 255")
  x <- floor(x)
  class(x) <- "uint8"
  return(x)
}

print.uint8 <- function(x) print(as.raw(x))

b02 <- uint8(  2)
b0a <- uint8( 10)
bff <- uint8(255)

b02
#> [1] 02

b0a
#> [1] 0a

b02 + b0a
#> [1] 0c

bff / b02
#> [1] 7f

Created on 2020-02-24 by the reprex package (v0.3.0)

Upvotes: 2

Related Questions