0
votes

I have a vector of int16 values that is represented in Matlab as a vector of chars. (reason for this at the end)

Now I just want to convert every two char values from the array to a single int16 value. When reading binary files, this can be accomplished by the precision parameter of fread() - is there a analogue function for data that is already stored in a vector?

My current workaround:

% 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');

Reason that the data is read as char vector: I read a file which contains binary that is encapsuled between some ASCII strings. In order to find the binary data, the strings have to be interpreted, for which I use regexp. Then I get the pure binary part (int16 values in a row) as a (char) string.

1

1 Answers

1
votes

Cast the chars to 8-bit numbers (integers), then typecast those to 16-bit integers:

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

Note you may want to use unsigned ints (uint16) depending on your use case.