Changing data type without changing bits

5 次查看(过去 30 天)
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

更多回答(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 CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by