, which
converts a hexadecimal representation of longitude or latitude into a
numeric coordinate, using the information in tutorial 7 and shown above
(and any other piece of information that may be useful).
myHex2IntFun <- function(x) {
# Get leading hex 'nibble' (thus the 3rd in the character string, the first 2 are prefix 0x)
leadingHex <- str_sub(x, 3, 3)
# Check whether it corresponds to a negative value
negativeValue <- leadingHex %in% c("8","9","a","b","c","d","e","f") # > 8: leading bit = 1 : negative
# Convert the hex to unsigned-integer
x_int <- strtoi(x, base = 16L)
# Convert to binary format
x_bin <- R.utils::intToBin(x_int)
# Check number of characters
nchar(x_bin) # should be 32, but is not
# Pad the bits with 0s or 1s (depending on negativeValue)
if(negativeValue) {
# Pad with ones
x_bin <- str_pad(x_bin, width = 32L, side = "left", pad = "1")
}else {
# Pad with zeros
x_bin <- str_pad(x_bin, width = 32L, side = "left", pad = "0")
}
# IF negative: apply bit-inverse
if(negativeValue) {
# Bit inverse
x_bin <- str_replace_all(x_bin, pattern = "1", replacement = "2")
x_bin <- str_replace_all(x_bin, pattern = "0", replacement = "1")
x_bin <- str_replace_all(x_bin, pattern = "2", replacement = "0")
}
# Check length of character vector
nchar(x_bin) # now indeed 32 bits
# Convert from binary to decimal integer
y <- strtoi(x_bin, base = 2L)
# IF negative: transform value
if(negativeValue) {
y <- -y + 1L
}
# return
return(y)
}