Disabling integer overflow capping for uint8 datatypes
11 views (last 30 days)
Show older comments
Hello!
I am currently in the middle of optimizing some high-performance code, and have run into a weird situation where I need integer overflow to occur on some uint8 variables. Unfortunately, it seems like MATLAB features datatype capping, meaning that when I perform the operation
uint8(100) * uint8(30)
I get a value of 255, where I would expect something like 184.
The same occurs when I perform addition:
uint8(100) + uint8(200)
Here, I also expect to get 44, but instead get 255.
Is there a way to turn this capping off, so that I can have the overflow occur? I understand that this could potentially be a "dangerous" operation to perform, but I really would benefit from having a way to test some code with integer overflow in MATLAB before I do any form of compilation or other code optimization work.
0 Comments
Answers (1)
Voss
on 20 Jun 2024
Edited: Voss
on 20 Jun 2024
I don't think you can disable integer overflow capping, but you could of course perform the operations on corresponding floating-point variables and then take the results mod 256.
x = uint8(100);
y = uint8(30);
z = uint8(200);
% original integer arithmetic
x * y
x + z
% with capping "disabled"
uint8( mod( double(x) * double(y) , 256) )
uint8( mod( double(x) + double(z) , 256) )
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!