A
atrac
Hello.
In an embedded system, I am reading a binary file. In this application
data are stored in the file as 16bit signed, ranging from -32768 to
32767
Now, I need to rescale this to an unsigned 16 bit, ranging from 0 to
65535.
I do it in this way:
unsigned short int udata; //16 bit unsigned
short int sdata; //16 bit signed
// some code here loads 16 bit signed value into "sdata", then:
if(sdata & 0x80) {
//this is a negative number. Complement, convert to unsigned
and rescale
udata = 32767 - (unsigned short int) ~sdata;
} else {
//this is a positive number. Convert to unsigned and rescale
udata = 32768 + (unsigned short int) sdata;
}
Now, to optimize the code, I thought I could also use:
udata = ((unsigned short int) (sdata ^ 0x8000) ) ;
however, this does not work when sdata = -1 (binary all 1's).
Is there a way to smartly solve this issue?
I mean to optimize the code to use less instructions.
Am I missing anything?
Of course this is the 16 bit case but the question could be extended
to 32 bit int.
In an embedded system, I am reading a binary file. In this application
data are stored in the file as 16bit signed, ranging from -32768 to
32767
Now, I need to rescale this to an unsigned 16 bit, ranging from 0 to
65535.
I do it in this way:
unsigned short int udata; //16 bit unsigned
short int sdata; //16 bit signed
// some code here loads 16 bit signed value into "sdata", then:
if(sdata & 0x80) {
//this is a negative number. Complement, convert to unsigned
and rescale
udata = 32767 - (unsigned short int) ~sdata;
} else {
//this is a positive number. Convert to unsigned and rescale
udata = 32768 + (unsigned short int) sdata;
}
Now, to optimize the code, I thought I could also use:
udata = ((unsigned short int) (sdata ^ 0x8000) ) ;
however, this does not work when sdata = -1 (binary all 1's).
Is there a way to smartly solve this issue?
I mean to optimize the code to use less instructions.
Am I missing anything?
Of course this is the 16 bit case but the question could be extended
to 32 bit int.