【问题标题】:Convert Matlab char array to other data type without changing binary data在不更改二进制数据的情况下将 Matlab char 数组转换为其他数据类型
【发布时间】:2017-12-06 09:33:45
【问题描述】:

我有一个 int16 值的向量,它在 Matlab 中表示为一个字符向量。 (原因在最后)

现在我只想将数组中的每两个 char 值转换为单个 int16 值。 在读取二进制文件时,这可以通过 fread() 的 precision 参数来完成——对于已经存储在向量中的数据是否有模拟函数?

我目前的解决方法:

% workaround using fread() to convert data type char -> int16
bytes = length(binary);
f = fopen('tmp', 'w+');
fwrite(f, binary);
fseek(f, 0, 'bof');
binary = fread(f, bytes/2, '*int16');

数据被读取为字符向量的原因:我读取了一个文件,其中包含封装在一些 ASCII 字符串之间的二进制文件。为了找到二进制数据,必须解释字符串,为此我使用正则表达式。然后我将纯二进制部分(连续的 int16 值)作为 (char) 字符串。

【问题讨论】:

    标签: arrays string matlab type-conversion


    【解决方案1】:

    将字符转换为 8 位数字(整数),然后将其转换为 16 位整数:

    s = 'abcd'
    b = cast(s, 'int8')      % Gives [97 98 99 100]
    i = typecast(b, 'int16') % Gives [25185 25699]
    

    请注意,根据您的用例,您可能希望使用无符号整数 (uint16)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-30
      • 1970-01-01
      • 2020-03-15
      • 2016-06-28
      • 2011-08-02
      • 2013-11-16
      • 1970-01-01
      相关资源
      最近更新 更多