你可以使用R中的以下方法从十六进制中获取32位小端值:

huangapple go评论73阅读模式
英文:

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

你可以使用R中的以下方法从十六进制中获取32位小端值:

根据 https://hexed.it/ 的信息,这些字节的32位整数(有符号或无符号)是658。如何从这些原始值中获取值658?请注意这是小端序排列。

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

你可以使用R中的以下方法从十六进制中获取32位小端值:

英文:

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

你可以使用R中的以下方法从十六进制中获取32位小端值:

答案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 &lt;- as.raw(c(146, 2, 0, 0))
x
# [1] 92 02 00 00
readBin(x, integer(), n=1, size=4, endian = &quot;little&quot;)
# [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 &lt;- function(raw_32bit) {
  if(!( inherits(raw_32bit, &#39;raw&#39;) &amp; length(raw_32bit) == 4)) {
    rlang::abort(&#39;raw_32bit must be a 32-bit raw vector&#39;)
  }
  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, &quot;raw&quot;, 20)[17:20])
&gt; 658

huangapple
  • 本文由 发表于 2023年3月4日 05:24:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75632002.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定