Re: any idea on how do i convert a string value to an byte
- From: "Micky" <micky@xxxxxxxxxx>
- Date: Sat, 3 Sep 2005 23:39:44 +0000 (UTC)
"ben" <ben@xxxxxxxxxx> wrote in message
news:eDDAkP4VFHA.3864@xxxxxxxxxxxxxxxxxxxxxxx
> any idea on how do i convert a string value to an byte
Assuming you mean converting numeric string values such as "15" and "127" to
their numeric form -- it's back to math basics (units, tens, hundreds...)
Start with the last character/digit and subtract 48 from its ASCII value.
E.g., "7" becomes 55, less 48 is 7. For the next digit (if any), subtract 48
and multiply by 10. And for the next (if any), subtract 48 and multiply by
100. Add the three results together.
Example code:
#include <math.h> // for the pow(x, y) function
bool ConvertStringToByte(/*in*/ LPCTSTR lpszString, /*out*/ BYTE* byte){
// cast the string pointer to a CString to simplify life...
CString string = (CString) lpszString;
// test for length (must be 1, 2 or 3 characters)
int len = string.GetLength();
if(len>3) return(false);
// use something larger than a BYTE to begin with
int iRetVal = 0;
// start with the last character/digit
int digit = len;
// loop through the characters one by one
for(int N=0; N<len; N++){
// obtain character, decrement digit
TCHAR ch = string.GetAt(--digit);
// ensure character is numeric
if(ch <48 || ch >57) return(false);
// use the for loop control variable (N) to raise 10 to the Nth
power
// e.g., 10^0 = 1, 10^1 = 10, 10^2 = 100, etc...
iRetVal += ((ch - 48) * (int) pow(10, N));
}
// iRetVal now holds a value between 0 and 999
if(iRetVal>255) return(false);
// now cast the result to a BYTE...
BYTE by = (BYTE) iRetVal;
// copy the result to the output parameter
memcpy(byte, &by, sizeof(BYTE));
// acknowledge success
return(true);
}
.
- Prev by Date: Re: DDV functions?
- Next by Date: Using COleCurrency with ODBC and Visual C++
- Previous by thread: Re: DDV functions?
- Next by thread: Using COleCurrency with ODBC and Visual C++
- Index(es):
Relevant Pages
|