What is the difference between int8(0x98), uint8(0x98), typecast(uint8(0x98), 'int8')
65 次查看(过去 30 天)
显示 更早的评论
>> A=int8(0x98)
A =
int8
127
>> B=uint8(0x98)
B =
uint8
152
>> C=typecast(uint8(0x98), 'int8')
C =
int8
-104
I want 0x98 to be handled as signed Integer. Expectation is a negative values (-104) - two's complement.
Why is the calculation A=int8(0x98) leading to 127 and not to -104.
3 个评论
Dyuman Joshi
2023-6-6
I don't understand, is using typecast() not satisfactory?
Or am I misunderstanding what you want to obtain? In that case, please specify.
A=int8(0x98)
B=uint8(0x98)
C=typecast(B, 'int8')
回答(2 个)
Steven Lord
2023-6-6
If you use the following syntax, you create a uint8 value and then cast that value to int8. Since the uint8 value is larger than intmax for int8, it saturates at intmax.
y1 = 0x98
z = int8(y1)
Why uint8 not int8? From that documentation page I linked above: "By default, MATLAB stores the number as the smallest unsigned integer type that can accommodate it."
Instead tell MATLAB you want an int8 (a signed 8-bit integer) value from the start. To do this add the "s8" suffix to the hex value.
y2 = 0x98s8
The typecast function works because it converts not the value stored in the input but the bit pattern of the input to the new type.
format hex % Show the hex digits of the bit pattern
y1
y2
0 个评论
Swastik Sarkar
2023-6-6
In MATLAB, the number 0x98 will be represented as 127 in int8 due to overflow.
It will map to the nearest endpoint of the range. This is how MATLAB handles the overflow instead of setting the sign bit, like you would see in C.
However while typcasting a uint to int, it does not truncate and keeps the last bit. Hence you get -104
Read the description in this page to understand it better: int8
5 个评论
Steven Lord
2023-6-7
The number range is limited to [0 .. 2^7-1]
The range of values that can be represented in the int8 data type is:
[intmin('int8'), intmax('int8')]
where 2^7-1 is:
2^7-1
So your statement is incorrect.
The defined number range [-2^7 .. -1] cannot be achieved: value saturates at 2^7-1 instead
Incorrect. If you try to cast a uint8 value to int8, anything greater than intmax of int8 becomes intmax of int8.
y = intmax('uint8')
z1 = int8(y)
If you try to typecast a uint8 bit pattern to int8 then you can easily obtain a negative int8 value.
z2 = typecast(y, 'int8')
But you can certainly create negative int8 values directly
y = int8(-1)
negative sign is not provided
Incorrect, as shown above.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Numeric Types 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!