필터 지우기
필터 지우기

Changing data type without changing bits

조회 수: 5 (최근 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 CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by