Click here to Skip to main content
15,917,565 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

can you please let me know how can I get unsigned long equivalent to signed long value??? i do not want code,i need formula.

Example: if signed long var = -15 then what will be equivalent value of var when it is unsigned?

Please reply.
Please note that i am not looking for code,i need formula only.
Posted

Most processors nowadays work with 2's complement representation. That means that to build the negative value of a number n the formula

nneg = (2**WordSize - n) mod 2**WordSize


is used. For a 32-bit processor and your example value 15 that would be

nneg = 2**32 - 15 = 4 294 967 281 = 0xFFFF FFF1


Some older processors use One's Complement representation. For them the formula is

nneg = (2**WordSize-1 - n) mod 2**WordSize


which means that the value 0 has two representations namily 0x00000000 and 0xffffffff.
 
Share this answer
 
Comments
pasztorpisti 23-Aug-12 10:00am    
+5, additional info: http://en.wikipedia.org/wiki/Two%27s_complement
nv3 23-Aug-12 10:02am    
Thanks!
JackDingler 23-Aug-12 10:59am    
Good answer. My 5
nv3 23-Aug-12 11:08am    
Thanks, Jack!
If you look here[^], climits.h contains the limits of types for your implimentation of C++ ( although it should not change ). I believe a signed number uses the highest bit to specific the sign. So, if you reverse the sign and add (ULONG_MAX - LONG_MAX), to get the value of the high bit in an unsigned long, I think that's your answer.
 
Share this answer
 
In C++ a signed long containing -15 is hex 0xFFFFFFF1. Copying that to an unsigned long gives the same hex value which is 4294967281 decimal. There is no formula for this, in code you just use the same value but ignore the sign bit and treat it as positive.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900