%% Bitwise Operations and Integer Overflows
% The implicit cast used to assign the intermediate value of a bitwise
% operation can result in an overflow. To preserve the rightmost bits of
% the result and avoid unexpected behavior, disable the chart property
% *Saturate on Integer Overflows*.

% Copyright 2019-2020 The MathWorks, Inc.

%%
% For example, both charts in this model compute the bitwise operation |y =
% ~u|. The charts compute the intermediate value for this operation by
% using the target integer size of 32 bits, so the 24 leftmost bits in this
% value are all ones. When the charts assign the intermediate value to |y|,
% the cast to |uint8| causes an integer overflow. The output from each
% chart depends on how the chart handles integer overflows.
% 
% * If *Saturate on Integer Overflow* is enabled, the chart saturates the
% result of the bitwise operation and outputs a value of zero.
% * If *Saturate on Integer Overflow* is disabled, the chart wraps the
% result of the bitwise operation and outputs its eight rightmost bits.

%%
model = 'sf_bitwise_not_saturation';
load_system(model)

% Delete all annotations at the top level of the model
ah = find_system(model, 'FindAll', 'on', 'type', 'annotation');
for i = 1:length(ah)
   ao = get_param(ah(i), 'Object');
   ao.delete;
end

% Suppress overflow diagnostics
Simulink.SuppressedDiagnostic(...
    {[model '/SaturationEnabled']},...
    'Stateflow:Runtime:DataSaturateError');
Simulink.SuppressedDiagnostic(...
    {[model '/SaturationDisabled']},...
    'Stateflow:Runtime:DataOverflowErrorMSLD');
preWarning = warning('off',... 
    'Stateflow:cdr:AvoidCombiningBitwiseOpsAndSaturate');

open_system(model)
sim(model)
warning(preWarning);

%%
% For more information, see
% <docid:stateflow_ug#mw_95ed7dfb-9104-462d-97f1-dbb541db2aac>.
