Skip to main content
gamedev.net
🔒 Locked

converting to binary

Started by hello_there Mar 11, 2004 at 3:20 AM 5 replies 500+ views
Original Post
hello_there
hello_there
How do you convert a number into binary form in c++?
____________How could hell be worse?
Sneftel
Sneftel
Hmm, smells like homework. What have you tried already? How are you thinking of going about it? What problems have you run into?


"Sneftel is correct, if rather vulgar." --Flarelocke
hello_there
hello_there
int n = 5;
String s = "";

int counter = 0;

while(n > 0)
{
int r = n%2;
s = (char)(''0'' + r) + s;
n = n/2;
}

well i have that but that''s in java. i need to convert it to c++.
____________How could hell be worse?
NaliXL
NaliXL
What do you mean by "convert"? Numbers are always stored in binary, doesn''t matter if it''s an integer or a float. You usually just can''t access them in their binary form in the source-code. Instead, use hexadecimal representations. If you really really need to access them as binary, write a function that takes care of it.

In the Delphi language, that''d be something like this:


// Function IntToBinary takes a byte (unsigned 8-bit int) and returns a string
function IntToBinary(YourInteger : Byte): String;
begin
case (YourInteger) of
// Hex notation in Delphi is done with a $ sign before the number
// Result is equivalant to C++''s "return" statement
$0 : Result := Result + ''0000'';
$1 : Result := Result + ''0001'';
$2 : Result := Result + ''0010'';
$3 : Result := Result + ''0011'';
$4 : Result := Result + ''0100'';
$5 : Result := Result + ''0101'';
$6 : Result := Result + ''0110'';
$7 : Result := Result + ''0111'';
$8 : Result := Result + ''1000'';
$9 : Result := Result + ''1001'';
$A : Result := Result + ''1010'';
$B : Result := Result + ''1011'';
$C : Result := Result + ''1100'';
$D : Result := Result + ''1101'';
$E : Result := Result + ''1110'';
$F : Result := Result + ''1111'';
end;
end;
Newbie programmers think programming is hard.Amature programmers think programming is easy.Professional programmers know programming is hard.
Sneftel
Sneftel
Let me get this straight. In order to complete your homework assignment, so far you''ve copy-and-pasted code you found on the internet, and now you want people to convert it from Java to C++ for you? Yikes.


"Sneftel is correct, if rather vulgar." --Flarelocke
hello_there
hello_there
i just want to know what this will be in c++

int n = 5;
String s = "";

int counter = 0;

while(n > 0)
{
int r = n%2;
s = (char)(''0'' + r) + s;
n = n/2;
}
____________How could hell be worse?
Sneftel
Sneftel
Yes, I know. Read the Forum FAQ on homework questions, and repost once you''ve done some real work.


"Sneftel is correct, if rather vulgar." --Flarelocke

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.