Continue to Site

Welcome to our site!

Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

  • Welcome to our site! Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

How to extract number from a string correctly? CCS

Status
Not open for further replies.
hi,

I wish to extract 9 and 46 from a string
"PORT 10,247,56,67,9,46\r\n"
, where \r is 0x0D and \n 0x0A

Note that the string is not ended with \0, so the string length is 24 bytes.
Note that also the number of bytes for each number is not fixed,
for example, "PORT 101,247,56,67,9,46\r\n" could be 25 bytes in length.

However, the maximum of each number is 255, which is FF in hex.

the 9 and 46 is a port number, which is 2350.
9 = 0x09, 46 = 0x2E;

2350 == 0x09 2E

In short, the function will return 0x092E.
I use str

to ease you to test the code, I paste the code i typed here,
This function will not work because *string_ptr only returns one byte.

int8 FTPGetRemotePort(BYTE *buffer) {
BYTE *string_ptr;
BYTE deliminator[] = "PORT ,\r\n";
BYTE i;
BYTE high_byte;
BYTE low_byte;

string_ptr = strtok(buffer, deliminator);

for (i = 0; i < 6; i++) {
string_ptr = strtok(NULL, deliminator);

if (i == 4) {
high_byte = *string_ptr;
}

if (i == 5) {
low_byte = *string_ptr;
}
}
return make16(high_byte, low_byte);
}
BYTE buffer[40];

buffer[0] = 0x50;
buffer[1] = 0x4f;
buffer[2] = 0x52;
buffer[3] = 0x54;
buffer[4] = 0x20;
buffer[5] = 0x31;
buffer[6] = 0x30;
buffer[7] = 0x2c;
buffer[8] = 0x32;
buffer[9] = 0x34;
buffer[10] = 0x37;
buffer[11] = 0x2c;
buffer[12] = 0x35;
buffer[13] = 0x36;
buffer[14] = 0x2c;
buffer[15] = 0x36;
buffer[16] = 0x31;
buffer[17] = 0x2c;
buffer[18] = 0x39;
buffer[19] = 0x2c;
buffer[20] = 0x34;
buffer[21] = 0x36;
buffer[22] = 0x0d;
buffer[23] = 0x0a;
 
Are you looking for the comma delimited strings 9 and 46, or the numbers in the 9 and 46 position, whatever they are?

If you are looking for 9 and 46, then use the strstr function. Looking at your code, it seems you are looking for the 5th and 6th tokens. In that case, I would suggest you use rindex to find the last comma, the number after that is one of the ones you want. Your string is not null terminated, so I would make a copy and terminate it if possible. Then change the comma you just found to a null and repeat, now you will get the 9.

If memory is tight, just replace one of the termination characters with a null. You can always change it back.
 
Status
Not open for further replies.

Latest threads

Back
Top