Search code examples
rhexbinaryfiles

How can I get the 32-bit little-endian value from hex in R?


I have a data file with the following hex values in bytes 17:20

92 02 00 00

According to https://hexed.it/, the 32-bit integer of these bytes (signed or unsigned) is 658. How can I get the value 658 from these raw values? Note that this is Little-endian ordered.

> readBin(img_path, "raw", 20)[17:20]
[1] 92 02 00 00

enter image description here


Solution

  • If you read from the file as character, you can use strtoi

    hex_to_int = function(x) {
      i = 256^(0:(length(x)-1)) * strtoi(x, base = 16L)
      sum(i)
    }
    
    x  = c("92", "02", "00", "00")
    hex_to_int(x)
    # [1] 658