Register FAQ / Rules Forum Spy Search Today's Posts Mark Forums Read
Go Back   MacRumors Forums > Apple Systems and Services > Programming > Mac Programming

Reply
 
Thread Tools Search this Thread Display Modes
Old Dec 16, 2005, 12:42 PM   #1
Soulstorm
macrumors 68000
 
Soulstorm's Avatar
 
Join Date: Feb 2005
Working with binary

I have written a little program in c++ to show the binary equivalent of a number:
Code:
void dispbinary(unsigned u){
	int t;
	for(t=128; t>0; t=t/2){
		if(u & t)	cout << "1";
		else		cout << "0";
	}
}
But now I want to do the opposite: I want to give a number in binary code and see it normally. for example I want to give "00001010" and receive "10" as a result. how do I do this?

I tried working with arrays (giving the number in an array) and then working with the array positions one by one to see if the number in place is "0" or "1". But I received an error saying that ISO C++ forbids comparison between pointers and integers...

What can I do?
Soulstorm is offline   0 Reply With Quote
Old Dec 16, 2005, 12:58 PM   #2
Mitthrawnuruodo
Moderator
 
Mitthrawnuruodo's Avatar
 
Join Date: Mar 2004
Location: Bergen, Norway
If you turn the binary number around yoo get 01010000. Then it shouldn't be too hard to calculate with a loop:

Your number down here
|
v

0 * 2^0 = 0
+
1 * 2^1 = 2
+
0 * 2^2 = 0
+
1 * 2^3 = 8
+
0 * 2^4 = 0
...

2 + 8 = 10

__________________
Those who fail to learn history are doomed to repeat it; those who fail to learn history correctly... why, they are simply doomed.
Mitthrawnuruodo is offline   0 Reply With Quote
Old Dec 16, 2005, 12:59 PM   #3
HiRez
macrumors 601
 
HiRez's Avatar
 
Join Date: Jan 2004
Location: Western US
Quote:
Originally Posted by Soulstorm
But now I want to do the opposite: I want to give a number in binary code and see it normally. for example I want to give "00001010" and receive "10" as a result. how do I do this?
Well one way to do it would be to receive the number as a string (array of chars), walk each character of the array from the right side and add up the numbers. Keep a variable that doubles each time through the loop that is the number you will add onto the result if you find a "1" in that position.
HiRez is offline   0 Reply With Quote
Old Dec 16, 2005, 02:29 PM   #4
robbieduncan
Moderator
 
robbieduncan's Avatar
 
Join Date: Jul 2002
Location: London
I assume from the above you are just treating all binary input as positive? If you want to be able to have negative numbers you might need to do some reading!

Two's Complement
robbieduncan is offline   0 Reply With Quote
Old Dec 17, 2005, 02:20 AM   #5
Soulstorm
Thread Starter
macrumors 68000
 
Soulstorm's Avatar
 
Join Date: Feb 2005
Quote:
Originally Posted by HiRez
Well one way to do it would be to receive the number as a string (array of chars), walk each character of the array from the right side and add up the numbers. Keep a variable that doubles each time through the loop that is the number you will add onto the result if you find a "1" in that position.
that was my idea too, but I encounter a problem:

I can't compare a pointer and an integer! Look:

Code:
if(p[i]=="1"){
code......
}
The compiler gets me an error saying "ISO C++ forbids comparison between pointers and integers". Why? How can I bypass that?
Soulstorm is offline   0 Reply With Quote
Old Dec 17, 2005, 02:40 AM   #6
HexMonkey
Administrator
 
HexMonkey's Avatar
 
Join Date: Feb 2004
Location: New Zealand
You need to use single quotes instead of double quotes for characters, ie:
Code:
if(p[i]=='1'){
code......
}
The reason you get that error is that strings are a pointer to their first character, while a character is essentially just an integer. So when you use the code p[i]=="1", you are comparing the ith character of p to the address of a '1' character.
HexMonkey is offline   0 Reply With Quote
Old Dec 17, 2005, 02:52 AM   #7
Josh396
macrumors 65816
 
Josh396's Avatar
 
Join Date: Oct 2004
Location: Peoria/Chicago, IL
Quote:
Originally Posted by robbieduncan
I assume from the above you are just treating all binary input as positive? If you want to be able to have negative numbers you might need to do some reading!

Two's Complement
Good ol' Two's Complement. That was probably the easiest part about EE.
Josh396 is offline   0 Reply With Quote
Old Dec 17, 2005, 03:08 AM   #8
HiRez
macrumors 601
 
HiRez's Avatar
 
Join Date: Jan 2004
Location: Western US
Quote:
Originally Posted by Soulstorm
[/code]
The compiler gets me an error saying "ISO C++ forbids comparison between pointers and integers". Why? How can I bypass that?
You need to dereference the pointer to get the value of what it points to (*p instead of p):
Code:
#include <stdio.h>
#include <math.h>
#include <string.h>

int main (int argc, const char * argv[]) {
    char *s = "10001001"; // test binary string
    char *p = s;
    int x = strlen(s) - 1; // exponent
    int result = 0;
	
    while (*p != '\0') {
        if (*p == '1') {
            result += pow(2, x);
        }
        p++;
        x--;
    }

    printf("binary %s in base 10 = %d", s, result);

    return 0;
}
There are multiple ways to skin this cat, this is just one.
HiRez is offline   0 Reply With Quote
Old Dec 17, 2005, 04:18 AM   #9
Soulstorm
Thread Starter
macrumors 68000
 
Soulstorm's Avatar
 
Join Date: Feb 2005
Quote:
Originally Posted by HexMonkey
You need to use single quotes instead of double quotes for characters, ie:
Code:
if(p[i]=='1'){
code......
}
The reason you get that error is that strings are a pointer to their first character, while a character is essentially just an integer. So when you use the code p[i]=="1", you are comparing the ith character of p to the address of a '1' character.
Thanks. That cleared things up a bit, and I can run the program nicely.

Quote:
Originally Posted by HiRez
You need to dereference the pointer to get the value of what it points to (*p instead of p):
Code:
#include <stdio.h>
#include <math.h>
#include <string.h>

int main (int argc, const char * argv[]) {
    char *s = "10001001"; // test binary string
    char *p = s;
    int x = strlen(s) - 1; // exponent
    int result = 0;
	
    while (*p != '\0') {
        if (*p == '1') {
            result += pow(2, x);
        }
        p++;
        x--;
    }

    printf("binary %s in base 10 = %d", s, result);

    return 0;
}
There are multiple ways to skin this cat, this is just one.
Thanks for taking the time to write/find the program to help me. I appreciate that, you helped me a lot.\

EDIT: And this is what I intended to do from the start
Code:
#include <math.h>
#include <iostream>
using namespace std;


int main (int argc, const char * argv[]) {
	int i, sum=0;
    char p[9]= "11011011";
	i=0;
	int exponent = 0;
	for(i=7; i>=0; i--){
		if(p[i]=='1'){
			cout << sum << "+2^" << exponent << "="; 
			sum=sum + (pow(2,exponent));
			cout <<sum << "\n";
		}
		exponent++;
	}
	cout << "Final result: " << p << " equals " << sum;
			
	return 0;
}

Last edited by Soulstorm; Dec 17, 2005 at 04:43 AM.
Soulstorm is offline   0 Reply With Quote
Old Dec 17, 2005, 10:19 AM   #10
Jordan72
macrumors member
 
Join Date: Nov 2005
Quote:
Originally Posted by Soulstorm
Code:
void dispbinary(unsigned u){
        int t;
        for(t=128; t>0; t=t/2){
                if(u & t)       cout << "1";
                else            cout << "0";
        }
}
I found this pretty clever. I'm just getting into bit maniputlaion, which is probably why. Did you come up with that yourself? I mean the idea where all the bits are zero in the right operand, except for the bit number you want to know about in the left operand through anding. (The dividing by two thing is cool too.)
Jordan72 is offline   0 Reply With Quote
Old Dec 18, 2005, 09:58 PM   #11
NewbieNerd
macrumors 6502a
 
Join Date: Sep 2005
Location: Chicago, IL
Send a message via AIM to NewbieNerd
Quote:
Originally Posted by Soulstorm
I have written a little program in c++ to show the binary equivalent of a number:
Code:
void dispbinary(unsigned u){
	int t;
	for(t=128; t>0; t=t/2){
		if(u & t)	cout << "1";
		else		cout << "0";
	}
}
Just a tip since you are learning about bit manipulation now. Whenever you divide by 2^x (2 to the x-th power), use t >>= x instead of t/pow(2,x), or in this case, do
Code:
t >>= 1
in place of
Code:
t /= 2
>> just means a right shift of the bits, and similarly you can use t << x to multiply t by 2^x. If you think about it, they are equivalent, but as you can imagine, shifting bits is much simpler, and thus faster, than actually dividing.
NewbieNerd is offline   0 Reply With Quote
Old Dec 19, 2005, 12:32 AM   #12
HiRez
macrumors 601
 
HiRez's Avatar
 
Join Date: Jan 2004
Location: Western US
Quote:
Originally Posted by NewbieNerd
>> just means a right shift of the bits, and similarly you can use t << x to multiply t by 2^x. If you think about it, they are equivalent, but as you can imagine, shifting bits is much simpler, and thus faster, than actually dividing.
True, although I think most modern compilers will automatically optimize division by a power of two to a bit shift, won't they?
HiRez is offline   0 Reply With Quote
Old Dec 19, 2005, 01:44 AM   #13
Soulstorm
Thread Starter
macrumors 68000
 
Soulstorm's Avatar
 
Join Date: Feb 2005
Quote:
Originally Posted by HiRez
True, although I think most modern compilers will automatically optimize division by a power of two to a bit shift, won't they?
Maybe certain compilers won't do that in C++. Since C++ leaves you with the ability to do anything in your system, it must also leave you with the choice to optimize the code yourself.

Quote:
Originally Posted by Jordan72
I found this pretty clever. I'm just getting into bit maniputlaion, which is probably why. Did you come up with that yourself? I mean the idea where all the bits are zero in the right operand, except for the bit number you want to know about in the left operand through anding. (The dividing by two thing is cool too.)
Yes, but this program will work for numbers that can be represented with 8 binary digits. If you want more, you simple multiply the "128" with 2 (this will give you 9 digits). If you want 10 digits, give "512", and so on...
Soulstorm is offline   0 Reply With Quote
Old Feb 9, 2014, 09:40 AM   #14
jakyshan
macrumors newbie
 
Join Date: Feb 2014
Quote:
Originally Posted by Soulstorm View Post
I have written a little program in c++ to show the binary equivalent of a number:
Code:
void dispbinary(unsigned u){
	int t;
	for(t=128; t>0; t=t/2){
		if(u & t)	cout << "1";
		else		cout << "0";
	}
}
But now I want to do the opposite: I want to give a number in binary code and see it normally. for example I want to give "00001010" and receive "10" as a result. how do I do this?

I tried working with arrays (giving the number in an array) and then working with the array positions one by one to see if the number in place is "0" or "1". But I received an error saying that ISO C++ forbids comparison between pointers and integers...

What can I do?
sorry for distrub
iam abeginner and i come to betwise operator and i m googling about this loop : can some one expline how its work this for loop thank you
jakyshan is offline   0 Reply With Quote
Old Feb 9, 2014, 09:57 AM   #15
subsonix
macrumors 68030
 
Join Date: Feb 2008
Quote:
Originally Posted by jakyshan View Post
sorry for distrub
iam abeginner and i come to betwise operator and i m googling about this loop : can some one expline how its work this for loop thank you
The variable t is a bitmask and it's initial value of 128 is 10000000. In each iteration t is divided by 2 which have the effect of shifting the 1 to the right, i.e 01000000, 00100000, 00010000 and so on. In the body the mask is then tested by using a bitwise 'and' with the original value 'u', the test is 'true' if the same bit is set in u and t.
subsonix is offline   0 Reply With Quote
Old Feb 16, 2014, 04:51 AM   #16
jakyshan
macrumors newbie
 
Join Date: Feb 2014
Quote:
Originally Posted by subsonix View Post
The variable t is a bitmask and it's initial value of 128 is 10000000. In each iteration t is divided by 2 which have the effect of shifting the 1 to the right, i.e 01000000, 00100000, 00010000 and so on. In the body the mask is then tested by using a bitwise 'and' with the original value 'u', the test is 'true' if the same bit is set in u and t.
thank you very much
jakyshan is offline   0 Reply With Quote

Reply
MacRumors Forums > Apple Systems and Services > Programming > Mac Programming

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump

Similar Threads
thread Thread Starter Forum Replies Last Post
Universal Binaries vmachiel Mac Basics and Help 5 Jul 6, 2011 01:38 PM
Snow leopard antivirus works with safari, but does it work with chrome? cloakedpegasus OS X 21 May 8, 2010 04:23 PM
Javascript not working with Safari but working fine with Firefox jive Web Design and Development 5 Jul 28, 2009 09:23 AM
internet only works with wi-fi... won't work with full 3g reception! numb120 iPhone Tips, Help and Troubleshooting 3 Mar 6, 2009 11:27 AM
My Lexicon Lambda works with GarageBand but I can't get it working with LE 8 king felix Digital Audio 0 Dec 24, 2008 03:02 PM


All times are GMT -5. The time now is 03:46 AM.

Mac Rumors | Mac | iPhone | iPhone Game Reviews | iPhone Apps

Mobile Version | Fixed | Fluid | Fluid HD
Copyright 2002-2013, MacRumors.com, LLC