How to convert a 24 bit, two’s complement value into a signed integer?

조회 수: 103(최근 30일)
I want to read an AD converter using the Raspberry Pi SPI interface controlled by Matlab. The AD converter outputs 24 bit data in the two's complement format, MSD first. The Matlab writeRead command returns the data as a row vector of data type char
How can I quickly translate the data into an integer of data type int32 ?
  댓글 수: 8
Balamurugan S
Balamurugan S 2018년 4월 19일
Thank you very much for your timely help Walter Roberson.

댓글을 달려면 로그인하십시오.

채택된 답변

James Tursa
James Tursa 2014년 6월 10일
편집: James Tursa 2014년 6월 10일
s = 2's complement 24-bit string to convert
b = [s([1 1 1 1 1 1 1 1]) s]; % sign extension
k = typecast(uint32(bin2dec(b)),'int32'); % equivalent decimal number
  댓글 수: 5
Guillaume
Guillaume 2014년 10월 17일
This is is obviously a 24-bit binary string. Hence the extension by 8 bits to 32 bits.

댓글을 달려면 로그인하십시오.

추가 답변(1개)

Murat Belge
Murat Belge 2014년 6월 10일
There is an example MATLAB class in Raspberry Pi support package that does something similar for MCP300x ADC's. Here is the readVoltage() method for this class:
function voltage = readVoltage(obj, adcChannel)
validateattributes(adcChannel, {'numeric'}, ...
{'scalar', '>=', 0, '<=', obj.NumAdcChannels-1}, '', 'adcChannel');
adc = obj.getAdcChannelSelect(adcChannel);
data = uint16(obj.spiObj.writeRead([1, adc, 0]));
highbits = bitand(data(2), obj.Lsb2);
voltage = double(bitor(bitshift(highbits, 8), data(3)));
voltage = (obj.VoltageReference/1024) * voltage;
end
where obj.Lsb2 is defined as bin2dec('00000011'). The value read from ADC is 10-bits stashed into two 8-bit values. The upper two-bits is in byte 2 and the 8 least significant bits are in byte 3.
You can take a look at the entire class definition here:
<Support package installe dir>\raspi\+raspi\+internal\mcp300x.m
  댓글 수: 1
Michael Simson
Michael Simson 2014년 6월 10일
편집: Michael Simson 2014년 6월 10일
Thank you for the example and reference. I appreciate your time.

댓글을 달려면 로그인하십시오.

Community Treasure Hunt

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

Start Hunting!

Translated by