Changing data type without changing bits
조회 수: 1 (최근 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.
댓글 수: 0
채택된 답변
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
2013년 9월 6일
편집: Azzi Abdelmalek
2013년 9월 6일
var1 = int16(652)
a=dec2bin(var1,16)
a=a(9:end)
out=bin2dec(a)
댓글 수: 0
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
댓글 수: 0
참고 항목
카테고리
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!