|
-
April 2nd, 2005, 01:42 PM
#1
minus number
hi all,
im trying to write a negative number on its binary form on a file and then i need to reconstruct these number again .........when i convert -5 to its binary equivelant i get 11111011 to convert this number to its decimal equivalent u will get 251 so;
i need a way to reconstruct the negative number?????
-
April 2nd, 2005, 03:38 PM
#2
Re: minus number
First, you should post the code you're using so we could see what you're doing wrong.
The signed integer -5 and unsigned integer 251 have the same bit representation. Except that the bits have different meaning, because the unsigned version does not have a sign bit.
-
April 2nd, 2005, 06:44 PM
#3
Re: minus number
When you "reconstruct" the number, reconstruct it to a signed char (or any signed integer type) as opposed to an unsigned integer type.
Old Unix programmers never die, they just mv to /dev/null
-
April 3rd, 2005, 04:40 AM
#4
Re: minus number
 Originally Posted by Alkingg
hi all,
im trying to write a negative number on its binary form on a file and then i need to reconstruct these number again .........when i convert -5 to its binary equivelant i get 11111011 to convert this number to its decimal equivalent u will get 251 so;
i need a way to reconstruct the negative number?????
And how do you convert it? You have to use the 2s-complement, that is, flip all bits and add one.
- Matthias
"C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do it blows your whole leg off." - Bjarne Stroustrup
-
April 3rd, 2005, 05:17 PM
#5
Re: minus number
Code:
char val=-5;
cout<< "signed value: "<<(int)val<<endl;
unsigned char uval=val;
cout<<"unsigned value: "<<(int)uval<<endl;
Output:
Code:
signed value: -5
unsigned value: 251
Last edited by RoboTact; April 3rd, 2005 at 05:19 PM.
"Programs must be written for people to read, and only incidentally for machines to execute."
-
April 4th, 2005, 09:33 AM
#6
Re: minus number
Indeed Alkingg,
Explicitly sumarizing the previous posts, most compilers for modern CPU architectures store the negative bit of a signed integer type in the highest bit position. This means that negative integers, at the bit level, look like large positive integers. If you really want to examine the bit stream, the you can shift the bits out one at a time.
Chris.
You're gonna go blind staring into that box all day.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|