How can I use bit operation functions like bitconcat with both fi and built-in integer types without branching on isfi?

7 views (last 30 days)
I'm working with bit operation functions (e.g., bitconcat) that only accept fi objects as input. My code sometimes deals with built-in integer types (like uint8, int16, etc.), so I currently check with isfi(var) and branch accordingly to convert to fi only when needed.
Is there a cleaner or more efficient way to ensure compatibility with bitconcat and similar functions, without manual branching on input type?
If I write:
a = uint8(2)
bitconcat(a)
I got error like: Input arguments must be fi objects.
Current workaround
if isfi(var)
% Already fi
else
var = fi(var, ...);
end

Accepted Answer

MathWorks Fixed Point Team
Use castIntToFi to handle both fi and integer types.
If you want your code to work with both built-in integer types and fi objects, you can use the castIntToFi utility. This function converts integer types to equivalent fi objects, and passes through fi objects unchanged—eliminating the need for explicit branching.
x = uint8(15); % Built-in integer type
y = fi(3, 0, 8, 0); % fi object
% Use castIntToFi to ensure both are fi objects
x_fi = castIntToFi(x);
y_fi = castIntToFi(y);
result = bitconcat(x_fi, y_fi); % Now works regardless of original type
  • If the input is already a fi object, castIntToFi returns it unchanged.
  • If the input is an integer type, it creates a fi object with the same value and numerictype.

More Answers (0)

Products


Release

R2024b

Community Treasure Hunt

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

Start Hunting!