MATLAB Answers

0

Why can't 32-bit values be converted to 24-bit values?

Asked by Hannah Peterson on 20 Aug 2019
Latest activity Commented on by Guillaume
on 22 Aug 2019
I have an array with 5 columns of data points and I need to convert the points from 32-bit to 24-bit. The cast or typecast functions don't support 'bit24' as the precision value.
Is there another way to do this? I also tried writing the values into a new binary file and writing them back out at 24-bit, but it writes them out as a double.

  4 Comments

Show 1 older comment
Note that it's not just matlab that does not have a 24-bit data type. The processors that matlab runs on (x86-64) and used to run on (x86) do not have 24-bit data types either.
For a while it was common to see audio DSP chips with 24 bits.
Oh yes, there's plenty of architectures that do support 24-bits integers (or fixed point) but none of them run matlab.

Sign in to comment.

Tags

1 Answer

Answer by Walter Roberson
on 20 Aug 2019
 Accepted Answer

MATLAB does not have any 24 bit data type.
typecast() is only for taking a block of memory and changing the interpretation of the block without altering any of the values -- for example, taking a pair of unsigned 8 bit integers and re-interpeting it as a signed 16 bit integer.
Are your values 24 bit signed integers that have been packed into 32 bit unsigned integers, four 24 bit values (96 bits) packed into 3 uint32 (96 bits) ? If so then what byte order has been used? An additional byte will need to be provided for each, and possibly bytes will need to be re-arranged. In my experience, 24 bit values are typically stored MSB first, which is not how bytes are arranged in any current release of MATLAB.

  2 Comments

As you mentioned columns, the following re-orders the data so that it writes out column by column. It assumes that the data is already in 32 bit integer format. It assumes that the data is in simple numeric form in Intel byte order ('little endian'), such as 258 (hex 0x00000102) being
>> typecast(uint32(258),'uint8')
1×4 uint8 row vector
2 1 0 0
-- that is, it assumes that 258 would be stored in memory in consecutive bytes as 2 1 0 0 which is normal for Intel architectures but is not "network byte order", "big endian" which would store 258 in memory as consecutive bytes 0 0 1 2. It assumes that the 8 MSB are to be discarded and the rest to be written out in MSB-first form, so that 258 would get written out as consecutive bytes [0 1 2] (the 0 that is the MSB having been discarded).
swapped = swapbytes(YourMatrix);
bytes = typecast(reshape(swapped.', 1, []),'uint8');
bytes(1:4:end) = [];
fid = fopen('OutputFileName.bin', 'w');
fwrite(fid, bytes);
fclose(fid)
Correction, it writes out row by row, all of the first row then all of the second and so on.

Sign in to comment.