math - Convert signed to unsigned integer mathematically -


i in need of unsigned 16 bit integer value in opc server can send signed 16 bit integer. need change signed integer unsigned mathematically unsure how. internet research has not lead me in right path either. please give advise? in advance.

mathematically, conversion signed unsigned works sending non-negative remainder of signed integer divided 1 + max, max maximum integer can write available number of bits, 16 in case.

this logic works follows signed integer s:

if s >= 0 return s else return 1 + max + s 

for convention work expected signed s must satisfy

- (1 + max)/2 <= s < (1 + max)/2 

in case, given have 16 bits, have max = 0xffff , 1 + max = 0x10000 = 65536.

note if codify negative integer convention, result have highest bit on, i.e., equal 1. way, highest bit becomes flag tells whether number negative or positive.

examples:

 2 -> 2  1 -> 1  0 -> 0 -1 -> 0xffff -2 -> 0xfffe -3 -> 0xfffd ... -15 -> 0xfff1 ... -32768 -> 0x8000 = 32768 (!) -32769 -> error: cannot codify using 16 bits. 

Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -