How do I convert a Finite Integer to Hexadecimal in Simulink with Support for Code Generation?

There is no "dec2hex" block in Simulink, so how do you go about converting finite integers to hexadecimal representation in Simulink, with support for code generation?

 Accepted Answer

This can be done with a "MATLAB Function" block.  If necessary, care must be taken to ensure that code can be generated from models that use this "MATLAB Function" block.  Here are some specific steps to achieve this workflow. If you do not have a need for code generation, you can skip the first step.
  1. Go into "Model Settings -> Code Generation -> Interface" and enable variable-sized signals.  Ensure that you are using a target that has support for variable-sized signals, as the hexadecimal output of the "MATLAB Function" block will be of type string that varies in length depending on the finite integer input.
  2. Create a "MATLAB Function" block.
  3. Add the code below into the "MATLAB Function" block.
function y = fcn(u)
y = string(dec2hex(u));
  1. While inside the "MATLAB Function" block, open the "Ports & Data Manager" window.
  2. Go to the output, "y", and change the data type to "string".
Now you will be left with a "MATLAB Function" block that takes a finite integer input, converts it to its hexadecimal representation, then outputs it as a string.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!