convert int16 to uint16 without losing information

36 views (last 30 days)
I have a range of int16 values from -32768 to 32767 and want to convert these to uint16 values from 0 to 65535. I can't get this to work. Negative values get truncated to zero.
  1 Comment
Adam
Adam on 1 Feb 2018
Edited: Adam on 1 Feb 2018
Can't you just cast to double, add 32768, then cast to uint16?

Sign in to comment.

Answers (3)

Bob Read
Bob Read on 1 Feb 2018
Thanks to the person who suggesting casting to double, that's solved my problem.
  2 Comments
Adam
Adam on 1 Feb 2018
If this is something you do more than once I'd recommend creating a function to do it though so you don't need to do the maths each time. There may be a function in Matlab that does this, but neither cast nor typecast do.
There are functions in the image processing toolbox that do some kind of more friendly casting though, I just can't remember what they are off-hand. They'd be no better than writing your own as above though.
Guillaume
Guillaume on 3 Apr 2018
The image processing functions are im2xxx, in this case, im2uint16. They're implemented as mex files and hopefully only involve bit twiddling so should be faster than converting to double and back (which is going to be slow relatively speaking).

Sign in to comment.


nicolas potier
nicolas potier on 30 Mar 2018
https://la.mathworks.com/help/matlab/ref/typecast.html?searchHighlight=typecast&s_tid=doc_srchtitle
Esta es la función que necesita. Espero le sirva - >> typecast ----->Guarda los datos y no los pierde
  2 Comments
Adam
Adam on 3 Apr 2018
typecast won't shift data to the new range, it will just wrap the data within the new data type e.g.
>> typecast( int16( -32768 ), 'uint16' )
ans =
uint16
32768
Guillaume
Guillaume on 3 Apr 2018
At that point, you only need to toggle the MSB and you're done.

Sign in to comment.


Guillaume
Guillaume on 3 Apr 2018
It's an old thread but since it's been revived: In theory, the following should be faster than transitioning to double as it's just very simple bit toggling:
testarray = [intmin('int16'), -1, 0, 1, intmax('int16')]
asuint16 = bitxor(typecast(testarray, 'uint16'), uint16(32768))
In practice it may be the same speed, depending on how uint16 is implemented. If it read 32768 as double then convert to uint16, then it'll be slow (As conversions between floating point and integers are a lot more involved than just bit twiddling)

Categories

Find more on Convert Image Type in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!