What would be the equivalent of :
For x = 0 To (Len(bin) - 1)
If Mid(bin, Len(bin) - x, 1) = "1" Then CDecimal = CDecimal + (2 ^ x)
Next x
in c++?? thx. :):):):)
Printable View
What would be the equivalent of :
For x = 0 To (Len(bin) - 1)
If Mid(bin, Len(bin) - x, 1) = "1" Then CDecimal = CDecimal + (2 ^ x)
Next x
in c++?? thx. :):):):)
Things like this are a lot easier to do if you think of your standard C string as an array:
Code:char *pcBin = "10101";
int iTemp = 0'
for(int i = 0; i < strlen(pcBin); i++) {
if(pcBin[i] == '1')
iTemp += 1 << i;
}
Than Parksie, but how come i dont get the same answer with the function u gave me?
What would :
iTemp = iTemp + (2^i)
be in c++?
You use the shift operators << and >> :)
For example 1 << 2 = 1 * 2^2
It's much easier to see when you look in binary. They shift everything one bit to the left or the right:
b0101010 << 1 = b1010100
b0101010 >> 3 = b0000101
This is why 2^i disappeared in my code. Anyway, what "different answer" did you get?
I am writing a dll that will send data to the parallel port. The functions in the dll will then be used in VB. I already have the funcs to do the conversions in vb, but i want to include them into my dll. (these funcs were the ones i posted in the Parallel Port-Urgent" thread. I AM USING 8-BIT BINARIES.
I thought
00000001 was 1
00000010 was 2
00000011 was 3
00000100 was 4
00000101 was 5
etc...
When i use the code you gave me when I put
00000101 it shows 6
or for:
11111111 it shows 0 instead of 255.
For example, i would get 255 for 11111111 in vb.
SORRY. My mistake. I was reading ion wrong way.
what a $#?@ i am! :) Thanks a lot. Also, how would i convert from a decimal to a binary, the same thing you gave me but vice-versa?
So
iTemp += 1 << i;
would be iTemp = iTemp + 2^i
in VB?
That's correct :)
Thanks a lot. May I ask you one more thing?:
how would I write a function thst would now convert from decimal to a binary?
Code:long Dec2Bin(long lNum, char *pcBuf) {
int i = 0;
while(lNum) {
if(lNum & 1) pcBuf[i] = '1';
else pcBuf[i] = '0';
lNum >>= 1;
i++;
}
pcBuf[i] = 0; // Null-terminated
return i;
}
void userfunc() {
char pcBuf[40];
Dec2Bin(27, pcBuf);
cout << pcBuf << endl;
}
Thanks a lot. I actually wasn't too far from that :) Anyways, thans a lot, Parksie:);) :p :) ;) :p :p :) :D :D
No problem :)
PortBits%(I) = PortNum% Mod 2
PortNum% = Fix(PortNum% / 2)
in c++? What would the Fix be?
Just cast it straight to an integral value to lose the fractional portion:
...produces "5" :)Code:float fNum = 5.4f;
int iOther = (int)fNum;
cout << iOther << endl;
Sorry if I annoy you, but for the dec2bin function, what should i change so that it display the "0" all the time.
eg: now if i put 3 it s gonna say 11
how would i change it so that it outputs 00000011?