Bitcmp - differences between uint8 and int8 assumedtypes
14 ビュー (過去 30 日間)
古いコメントを表示
Hi,
I am using the function bitcmp for a school project and I came across a strange behaviour of this function, shown below:
>> a = bitcmp(53, 'int8')
a =
-54
>> b = bitcmp(53, 'uint8')
b =
202
Assuming the decimal defined in this example is well within the 8 bit representation (both signed and unsigned ranges), why is the outcome different? I was expecting it to be exactly the same.
Do you know which type of operation is bitcmp performing for uint8 and int8 types? I would like to do the same procedure "manually" to better understand this function.
Thanks
0 件のコメント
回答 (1 件)
Walter Roberson
2020 年 11 月 17 日
bitxor(int8(53), int8(-1))
bitxor(uint8(53), uint8(255))
typecast(int8(-54), 'uint8')
You should not be expecting the same result for the two. If you are expecting -54 for both, then you have the problem that negative values are out of range for uint8. If you are expecting 202 for both, then you have the problem that values > 127 are out of range for int8.
If you are using signed integers, then bitwise complement of a positive number is always negative, because the sign bit gets flipped. If you are using signed integers, then bitwise completement of a negative number is positive unless the number is the one with all bits set (in which case the result is 0), because the sign bit gets flipped.
If you are using unsigned integers, then bitwise complement of a number less than half of the maximum is always greater than half of the maximum, because the most significant bit gets flipped. If you are using unsigned integers, then bitwise complement of a number greater than half of the maximum is always less than half of the maximum, because the most significant bit gets flipped.
6 件のコメント
Steven Lord
2020 年 11 月 22 日
Look at the binary representation.
dec2bin(int8(53), 8)
The complement of that is 11001010. If we use that bit pattern to create a signed 8-bit integer:
x = 0b11001010s8
Walter Roberson
2020 年 11 月 23 日
x = 0:10;
[x; bitcmp(int8(x))]
Notice the pattern: for values up to 127, bitcmp(x) is -x-1 . Or to look at it another way, the sum of x and bitcmp(x) is -1 .
00110101
11001010
--------
11111111
In every case with bitcmp, 0 is replaced by 1 and 1 is replaced by 0, so the sum of the value and its bitwise complement will have 1 in every place -- either it was originally 0 and the complement was 1, or else it was originally 1 and the complement was 0. It is never possible to have a carry when you add together a value and its bitwise complement, and its is never possible to end up with a 0 in any position.
You can also think of this as starting with the all-1 value, and subtracting the bitwise representation of the original value to get the bit representation of the new value.
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!