convert hex to dec

SgtWookie

Joined Jul 17, 2007
22,230
#include <stdlib.h>
#include <stdio.h>

int main(void)
{
char s[] = "2F";
unsigned long x;
x = strtoul(s, 0, 16);
printf("The value represented by the string \"%s\" is\n"
"%lu (decimal)\n" "%#lo (octal)\n" "%#lx (hex)\n",
s, x, x, x);
return 0;
}

[output]
The value represented by the string "2F" is
47 (decimal)
57 (octal)
0x2F (hex)
 

BMorse

Joined Sep 26, 2009
2,675
what is char s[]
Chr$ Function ;Returns a String containing the character associated with the specified character code.
Syntax
Chr$(charcode)
The required charcode argument is a Long that identifies a character.
Remarks
Numbers from 0 – 31 are the same as standard, nonprintable ASCII codes. For example, Chr(10) returns a linefeed character. The normal range for charcode is 0 – 255. However, on DBCS systems, the actual range for charcode is -32768 to 65535.
Note The ChrB function is used with byte data contained in a String. Instead of returning a character, which may be one or two bytes, ChrB always returns a single byte. The ChrW function returns a String containing the Unicode character except on platforms where Unicode is not supported, in which case, the behavior is identical to the Chr function.
 

Thread Starter

wheetnee

Joined Oct 1, 2009
28
string lookfor = "41";
if ( str.substr(0,lookfor.length()) == lookfor ) // if the line starts with "41"
cout << str.substr(lookfor.length()) << '\n'; //str.substr(lookfor.length()) is the line after the "41"
str2 = str.substr(lookfor.length());


//splits into digits/numbers
int i;
string str3;
for (i=2; i<=str2.length()+1; i+= 2){
cout << str.substr(i,2) << "\n"; //str.substr(i,1)are individual stuff in this case ONLY
str3 = str.substr(i,2);



//stores separated stuff into vector [unknown type]
the_vector.push_back( str3 );
}


//accessing the vectors
int j;
for (j=0; j<the_vector.size(); j++){ //prints your vector
cout << the_vector.at(j)<< "\n"; //
} //




//determing the type of data (first 2 digits after 41)
string num = "11";
if (the_vector.at(0) == num){
cout << "ok it's throttle position"<< "\n";
} else {
cout<< "it's something else"<< "\n";
}



//determining A (3rd 4th digits after 41)

string str4;
for (i=4; i<=str2.length()+1; i++)
{
cout << str.substr(i,1) << "\n"; //
str4 = str.substr(i,1);
the_vector.push_back( str4);
}


for(j=0; j<the_vector.size(); j++)
{
cout << the_vector.at(j)<<"\n";
}





im trying toconvert to hex to dec from a string i split
i split it into -> 2 F and i have to convert to hex to dec
 

BMorse

Joined Sep 26, 2009
2,675
try something like this:
Rich (BB code):
int HexToDec(const char* strHex)
{
  int nFactor = 1;
  int nRetVal = 0;

  for(char* p = strHex + strlen(strHex); p >= strHex; --p)
  {
     if(p[0] < 'A') nRetVal += nFactor * (p[0] - '0');
     elseif(p[0] < 'a') nRetVal += nFactor * (p[0] - 'A' + 10);
     else nRetVal += nFactor * (p[0] - 'a' + 10);
     nFactor *= 16;
  }
  return nRetVal;
}
 

BMorse

Joined Sep 26, 2009
2,675
There is a simpler algorithm, you can run through the string in from the start to the end.
Example:

hex = 0xF5A8
=(((0xF)*16 +0x5)*16 +0xA)*16 +0x8
At each iteration, you just need to multiply the accumulator by 16, and add the new digit.

My .02
 

Thread Starter

wheetnee

Joined Oct 1, 2009
28
For this assignment a OBD II Diagnostic tool was connected to a Ford F-150 truck and data collected on two short trips. The diagnostic tool queried the onboard computer once every 500 milliseconds for:

  • Throttle position
  • Engine RPM
  • Vehicle speed
  • Air Intake temperature
  • Engine Load
  • Mass air flow
  • Engine Coolant Temperature

Here is a sample of the data. Time 1
410F49
410556
41112F
410C0000
410D00
Time 2
410400
4110000A
410F49
NO DATA
410556
Each line that begins with "Time" indicates that the next sample interval has started. So in the above all the lines between "Time 1" and "Time 2" represents one sample set. Lines that do not begin with "Time" or "41" can be ignored. Each line that begins with 41 is followed by 2 or more pairs of characters and is a piece of data sent by the onboard computer in response to a request for data. In the output, each pair of characters represents a hex digit. The line, after the 41 is striped out, is interpreted according to the OBD-II PID rules. The table identifed by the link in the previous sentence summarizes each response code and provides information on how to interpret each line. Note that with respect to the table, all of the data is collected in mode 01 so you need to look down the PID column to find the rule. For example the code 4110000A is interpreted as follows:

  • 41 - starting sequence for a line - if a non-time "Time" line doesn't start with 41 ignore the data line
  • 10 - is MAF (mass air flow)
  • 00 - is the "A" value in hex (recall hex is base 16 so 0 hex is 0 decimal) 0A - is the "B" value in hex (hex A is 10 in decimal)
The computed value is then ((256*0)+10)/100 which is 0.10g/s of air flowing through the air intake. That's not very much and probably means the engine hasn't started. If the value had been 411008AF the calculation would have been (256 * 8 + 175)/100 = 22.23g/s Note that AF is 175 in hex. (Note that when interpreting this in hex A is 10, B 11, C 12, D 13, E 14,and F is 15 in decimal. To convert a pair of hex digits to decimal, convert the first "character" to decimal then multiply it by 16 and add the 2nd digit, converted to decimal.) The basic program will do the following:
  1. read a line
  2. if the line is a time line update the display and wait some amount of time
    else read and parse the line and update the "device" data
  3. go to 1
During the update phase the program will update the display based on the current information for the device. The program will then wait a specified amount of time before reading the next set of data. If the program waits 500ms the display would be updating in "real time." If the program waited 250ms it would be running at double speed and if it waited 100ms it would be running at 5 times faster than real time, and so on. Although your program is to read and store the most recent of each of the types of data being sampled, your display only has to have two gauges, you can have more if you want. Each gauge is to display the current reading of one of the pieces of sampled data or some information that is derived from it. Regardless of what you choose to display it needs to be updated in "realtime". As an example of a derived value, the MAF data in conjunction with the vehicle's velocity can be used to compute the current fuel mileage (economy) using the formulas described in this PDF document. The document provides the calculations in miles per gallon but there is sufficient information to perform variants of this like litres per 100 kilometres. The format of the display is of your choosing and could be analog gauges, digits, stacked bars, a combination, or something else.
Some Design Requirements

Your program must:
  • Prompt for the file name to read the OBD-II sample data from
  • Prompt for the pause interval in milliseconds (1000 milliseconds = 1 second)
  • Have at least one user defined class (Objects that "hold" dervied data values, or a gauge)
  • Make use of at least two instances (objects) of the user defined class.
Comments on doing the assignment

Since this is a non-core activity it is possible that you may encounter issues not explicitly identified in this assignment. In situations like that you are to make a reasonable decision and justify your decision. This program is to be substantially your own but you are free to consult published solutions to subsets of problems, but you must explicitly acknowledge this in the code. As an example if you found a snippet of code to convert hex characters to an integer then you are free to use or adapt the code provide that you acknowledge that the code is borrowed and from where. Similarly you must acknowledge the original author if your code is based. Acknowledgement is to take the form of identifying the author and sufficient information so that someone else can locate the source. You may find the code in the text on graphics helpful. You do not have to acknowledge that code unless you basically cut and paste parts of it not do you have to acknowledge the code provided in the "getting started" VehicleCompDisplay.zip file. With respect to the sample project, observe the processing loops for updating the displays. Basically you need to loop reading and updating the data and then when reading a "Time" line pause for a certain number of milliseconds. Use the provide DisplaySleep()code. Note that each time you want your display to be updated you need to invoke redraw() on the window and then you need to do a Fl::check(). Fl::check() causes the display to be updated and then returns control to the caller. Typically you don't call redraw() and Fl::check() until you have made all the updates to the window and want them to be displayed. The piece of the code that "ticks" a clock is pretty close to what you will need to do. Basically you just augment the first part with a loop that reads and when it is done it modifies the display, redraws the window() and then calls DisplaySleep().
Some of the chapters in the text that you may find helpful are:

  • Chapter 10 - Input and Output Streams
  • Chapter 11 - Customizing Input and Output (especially 11.5 and 11.6)
  • Chapter 13 - Contains lots of useful information on manipulating shapes and text. L:\Courses\cs260 - the bits of sample code from A1.
  • Appendix C - Getting Started with Visual Studio
  • Appendix D - Installing FLTK - note that FLTK is installed in L:\Courses\cs260.
There are also a couple of sample projects using the graphics package that you might want to check out. One just uses FLTK and the other uses FLTK as wrapped in the graphics routines used in the text. Although not required, the easiest way to get going with these examples is to copy Chap13Demo directory in the
L:\Courses\cs260 directory. When doing the assignment, there is no expectation that you use the FLTK routines directly but that you use the routines indirectly through the graphics routines described in the text. Note: that if you copy the sample programs to your own machine you may need to tell visual studio where to locate the FLTK .h files and libraries.
As suggested above, when you are ready to do the assignment unzip the VehicleCompDisplay.zip file and use the files there as the starting point. The easiest approach is probably to remove the code from the main program that you don't need and replace it with your own and add any new .h or .cpp files to the project.
 
Top