Handle two\'s complement numbers.

SignExtend.cpp

Committer:
Owen
Date:
2011-01-20
Revision:
0:b495118be5a7

File content as of revision 0:b495118be5a7:

#include "mbed.h"
#include "assert.h"

int SignExtend( int value, const int bit_width )
{
    assert( ( bit_width > 1) && ( bit_width < (8*sizeof(int)) ) );

    value &= ( (1<<(bit_width)) - 1 ); /* Clear out any extra MSB data */

    if ( ( value & ( 1 << (bit_width-1) ) ) != 0 )
    {
        /* value IS negative */
        value -= (1<<bit_width);
    }

    return value;
}