英文:
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
根据 https://hexed.it/ 的信息,这些字节的32位整数(有符号或无符号)是658。如何从这些原始值中获取值658?请注意这是小端序排列。
> readBin(img_path, "raw", 20)[17:20]
[1] 92 02 00 00
英文:
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
答案1
得分: 1
如果你将文件作为字符读取,你可以使用 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
希望这对你有所帮助。
英文:
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
答案2
得分: 1
如果您有一个原始向量,您可以使用readBin
函数将其转换为整数。例如:
x <- as.raw(c(146, 2, 0, 0))
x
# [1] 92 02 00 00
readBin(x, integer(), n=1, size=4, endian = "little")
# [1] 658
请注意,以上是代码示例,用于将原始向量转换为整数。
英文:
If you have a raw vector you can use readBin
to convert to integer. For example
x <- as.raw(c(146, 2, 0, 0))
x
# [1] 92 02 00 00
readBin(x, integer(), n=1, size=4, endian = "little")
# [1] 658
答案3
得分: 0
以下是代码的翻译部分:
# 一种手动执行的方法是:
get_32bit_unsigned <- function(raw_32bit) {
if (!(inherits(raw_32bit, 'raw') & length(raw_32bit) == 4)) {
rlang::abort('raw_32bit必须是一个32位原始向量')
}
width_in_bits = rawToBits(raw_32bit)
v = 0
for (i in 1:length(width_in_bits)) {
v = v + 2^(i-1) * as.integer(width_in_bits[i])
}
return(v)
}
get_32bit_unsigned(readBin(img_path, "raw", 20)[17:20])
# 输出:658
希望这对你有所帮助。如果你需要进一步的帮助,请随时提问。
英文:
One way to do this is manually:
get_32bit_unsigned <- function(raw_32bit) {
if(!( inherits(raw_32bit, 'raw') & length(raw_32bit) == 4)) {
rlang::abort('raw_32bit must be a 32-bit raw vector')
}
width_in_bits = rawToBits(raw_32bit)
v = 0
for(i in 1:length(width_in_bits)) {
v = v + 2^(i-1)*as.integer(width_in_bits[i])
}
return(v)
}
get_32bit_unsigned(readBin(img_path, "raw", 20)[17:20])
> 658
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论