convert int16 to uint16 without losing information
36 views (last 30 days)
Show older comments
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
Answers (3)
Bob Read
on 1 Feb 2018
2 Comments
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
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).
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
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
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)
0 Comments
See Also
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!