Changing data type without changing bits
5 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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.
0 commentaires
Réponse acceptée
Walter Roberson
le 6 Sep 2013
Modifié(e) : Walter Roberson
le 6 Sep 2013
t = typecast(var1, 'uint8'); %presuming var1 is int16
var2 = t(2); %second byte
1 commentaire
Plus de réponses (2)
Azzi Abdelmalek
le 6 Sep 2013
Modifié(e) : Azzi Abdelmalek
le 6 Sep 2013
var1 = int16(652)
a=dec2bin(var1,16)
a=a(9:end)
out=bin2dec(a)
0 commentaires
Anand
le 6 Sep 2013
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
0 commentaires
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!