0

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.

0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.