R 如何将原始向量中的字节转换为ascii空间

发布于 2025-01-12 06:35:26 字数 331 浏览 3 评论 0原文

我正在阅读一些由 C 代码创建的非常旧的文件,这些文件由标头 (ASCII) 和数据组成。我使用 readBin() 来获取标头数据。当我尝试将标头转换为字符串时,它失败了,因为有 3 个“坏”字节。其中两个是二进制 0,另一个是二进制 17 (IIRC)。

如何将坏字节转换为 ASCII SPACE? 我尝试过以下代码的某些版本,但失败了。

      hd[hd == as.raw(0) | hd  == as.raw(0x17)] <- as.raw(32)

我想用空格替换每个错误值,这样我就不必在解析从 hd 派生的字符串时重新计算所有固定数据位置。

I am reading some very old files created by C code that consist of a header (ASCII) and then data. I use readBin() to get the header data. When I try to convert the header to a string it fails because there are 3 'bad' bytes. Two of them are binary 0 and the other binary 17 (IIRC).

How do I convert the bad bytes to ASCII SPACE?
I've tried some versions of the below code but it fails.

      hd[hd == as.raw(0) | hd  == as.raw(0x17)] <- as.raw(32)

I'd like to replace each bad value with a space so I don't have to recompute all the fixed data locations in parsing the string derived from hd.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

拥抱没勇气 2025-01-19 06:35:26

我通常只是将其转换为整数。

假设我们有这个原始向量:

raw_with_null <- as.raw(c(0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x00, 
                          0x57, 0x6f, 0x72, 0x6c, 0x64, 0x21))

如果我们尝试将其转换为字符,因为空字节,我们会得到一个错误:

rawToChar(raw_with_null)
#> Error in rawToChar(raw_with_null): embedded nul in string: 'Hello\0World!'

很容易转换为数字并用 32 替换任何 0 或 23(ascii 空格)

nums <- as.integer(raw_with_null)

nums[nums == 0 | nums == 23] <- 32

然后我们可以转换 nums 返回原始,然后返回字符:

rawToChar(as.raw(nums))
#> [1] "Hello World!"

reprex 包 (v2.0.1)

I normally just go through a conversion to integer.

Suppose we have this raw vector:

raw_with_null <- as.raw(c(0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x00, 
                          0x57, 0x6f, 0x72, 0x6c, 0x64, 0x21))

We get an error if we try to convert it to character because of the null byte:

rawToChar(raw_with_null)
#> Error in rawToChar(raw_with_null): embedded nul in string: 'Hello\0World!'

It's easy to convert to numeric and replace any 0s or 23s with 32s (ascii space)

nums <- as.integer(raw_with_null)

nums[nums == 0 | nums == 23] <- 32

We can then convert nums back to raw and then to character:

rawToChar(as.raw(nums))
#> [1] "Hello World!"

Created on 2022-03-05 by the reprex package (v2.0.1)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文