Changing the number of bits for a value

20 views (last 30 days)
Korie Wagner
Korie Wagner on 6 Aug 2020
Commented: Fangjun Jiang on 11 Aug 2020
Is there a way to put information into a specified number of bits? Specifically, the output of my code will be two separate values, one needs to be a 27-bit integer and the other needs to be a 12-bit integer. They are both currently doubles. Does matlab support dataypes with unconventional numbers of bits?

Answers (2)

Fangjun Jiang
Fangjun Jiang on 6 Aug 2020
help fixdt
  2 Comments
Korie Wagner
Korie Wagner on 11 Aug 2020
I am still confused about how to utilize this function. If I were to save the variable "a = 5" and I wanted it to be a 27-bit integer, would this function work to update the datatype and how exactly would I implement this change?
Fangjun Jiang
Fangjun Jiang on 11 Aug 2020
I thought of Simulink without hesitation. For MATLAB, see Walter's answer. For Simulink
a=Simulink.Parameter;
a.Value=5;
a.DataType='fixdt(0,27,0)';
Then, drag a Constant block and specify the value as "a". Show "Port Data Types". It will show data type as ufix27.
Or, define your own data type and apply it everywhere
MyUint27=fixdt(0,27,0);
a.DataType='MyUint27';

Sign in to comment.


Walter Roberson
Walter Roberson on 11 Aug 2020
You can create a numerictype() object that is a description of a fixedpoint datatype. When you need to convert a non-fixedpoint number use fi() passing in the value and the numerictype template.
Once a value is converted to fixedpoint then you can use arithmetic operations on it at need.
Note that individual fixedpoint objects will need the next major power of 2 bits to store in memory in MATLAB. A 27 bit number will need 32 bits to store plus have additional overhead due to having to go through class methods at the MATLAB level.
There are two major reasons to use fixedpoint objects at the MATLAB level:
  • you need to interface to something external that has that representation; or
  • you are creating code to be deployed to DSP or FPGA, where you might not have a floating point core and where you might literally be representing a value by that many bits at the hardware level. No point in using a larger die to hold additional gates that are not going to be used for the application.

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!