Changing data type without changing bits

1 回表示 (過去 30 日間)
Milan
Milan 2013 年 9 月 6 日
Hi,
I want to convert integer data type without changing bits.
For example, say I have a variable var1 = int16(652) = 0000 0010 1000 1100 in binary representation.
I want to set a variable var2 to be of int8 type, and is equal to the bottom 8 bits of var1.
IE, var2 = 1000 1100 in binary representation. This is equivalent to -116 (2s complement binary representation of the decimal value).
var2 = int8(var1) does not accomplish this....it takes the value 652, rounds it to the highest possible int8 value (127) and returns that value 127 .... which is 0111 1111 in binary representation....not what I want.
Is there a workaround to this.
I know reinterpretcast exists but it requires the fixed point tool license which I do not have.

採用された回答

Walter Roberson
Walter Roberson 2013 年 9 月 6 日
編集済み: Walter Roberson 2013 年 9 月 6 日
t = typecast(var1, 'uint8'); %presuming var1 is int16
var2 = t(2); %second byte
  1 件のコメント
James Tursa
James Tursa 2013 年 9 月 6 日
Or 'int8' if OP wants sign bit as stated.

サインインしてコメントする。

その他の回答 (2 件)

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 9 月 6 日
編集済み: Azzi Abdelmalek 2013 年 9 月 6 日
var1 = int16(652)
a=dec2bin(var1,16)
a=a(9:end)
out=bin2dec(a)

Anand
Anand 2013 年 9 月 6 日
Firstly, 127 is the largest positive number that can be represented with the int8 type, because the first bit is a sign bit. You are probably looking for uint8.
If this is the case, you can do this using bit-wise operations in MATLAB as follows.
>> a = int16(652)
>> msk = int16(255);
The binary representation for this mask is 8 1's followed by 8 0's.
>> dec2bin(msk,16)
ans =
0000000011111111
Use bitand with the mask we created to mask out the first 8 bits.
>> b = bitand(a,msk)
ans =
140
>> b = uint8(b)
ans =
140

カテゴリ

Help Center および File ExchangeNumeric Types についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by