a simple stupid question :)

Started by
7 comments, last by Chris Hare 19 years, 7 months ago
Okay i got this simple (and stupid) question i got a char * data contains several bytes.. lets say 8 (size changes though), would be 01 02 03 04 05 06 07 08 okay, i need to run a switch on it, like switch(data) { case 0x01: blabla; return; }; now, i need to get the first byte only, (0x01) to check it.. like data[0], but that wont work (or atleast aint working here). anyone got an idea of super quickly getting the first byte only into the swich check ? Thanks
Advertisement
data[index] should work, what error are you getting?
the id doesnt match the data

eg 01 02 03 04 05 06 07

wont say its a 0x01

eg 01

will say its a 0x01
Subscripting should definately work, provided your pointer is valid...
#include <iostream>using namespace std;int main(){	char buff [] = { 0x0, 4, 3, 1, 6, };	char* ptr = buff;	switch(ptr[0])	{	case 0x0:		cout << "Zero" << endl;		break;	default:		cout << "Nonzero" << endl;		break;	}	return 0;}
Chris Hare is right. When you did
switch (data)
you were actually switching based on the value of "data", which is simply a pointer. What you want to switch on is what data points to, which is
data[0]
or equivalently
*data
“[The clergy] believe that any portion of power confided to me, will be exerted in opposition to their schemes. And they believe rightly: for I have sworn upon the altar of God, eternal hostility against every form of tyranny over the mind of man” - Thomas Jefferson
still aint working, here is what i got so far

void checkout(char* buffer){	char * ptr = buffer;	switch(ptr[0])	{		// general stuff		case 0x67:			do something		break;		default:			do something else		break;	};}


now, if my buffer looks like this

67 00 00 01 20 22 02 00
it will use default

if my buffer looks like this
67
it will use the case 0x67
0x67 is very different to 67. 67 is, well, 67 in base 10 [decimal], but 0x67 is in base 16 [hexadecimal], or 6 * 16 + 7 * 1 = 103 in decimal. So, just use plain 67.
im guessing i need a workaround, since i need to compare hex values.


case 0x67
case 0x68

and so on.

so my guess is, i need to convert the char * buffer to a int * buffer or something.
0x67 will fit into a char var, it's just that you need to ensure you write 0x67 to the array and not 67. That is, if you are using hexadecimal, use it all the way through your relevant code.

This topic is closed to new replies.

Advertisement