Reputation: 517
I have a byte array such as 0x21, 0x0D, 0x01, 0x03, 0x31, 0x32, 0x33
which containts the ascii string "123"
with a length of 3. (string starts at 0x03, 0x31, 0x32, 0x33)
I'm learning, So would somebody be able to show me how to get the output "123"
from it and put it inside a char*
? Many thanks
BYTE Data[] = { 0x0D, 0x01, 0x03, 0x31, 0x32, 0x33 };
int Length = Data[2];
//Extract string "123" from Data and store as char* ?
Upvotes: 1
Views: 356
Reputation: 98088
If you have char sized data in BYTE type:
#include <iostream>
typedef unsigned char BYTE;
BYTE Data[] = { 0x0D, 0x01, 0x03, 0x31, 0x32, 0x33 };
int main() {
std::string str(reinterpret_cast<char*>(Data) + 3, 3);
std::cout << str << std::endl;
const char * c = str.c_str();
std::cout << c << std::endl;
return 0;
}
Upvotes: 2
Reputation: 121809
Here is one example:
#include <windows.h> // typedef for BYTE
#include <stdio.h>
#include <ctype.h> // isnum(), isalpha(), isprint(), etc
BYTE bytes[] = {
0x21, 0x0D, 0x01, 0x03, 0x31, 0x32, 0x33
};
#define NELMS(A) (sizeof(A) / sizeof(A[0]))
int
main(int argc, char *argv[])
{
char buff[80];
for (int i=0, j=0; i < NELMS(bytes); i++) {
if (isprint(bytes[i])) {
buff[j++] = bytes[i];
}
}
buff[j] = '\0';
printf ("buff=%s\n", buff);
return 0;
}
EXAMPLE OUTPUT:
buff=!123
You'll notice that "0x21" is a printable character ("!"). Instead of "isprint()" (is a printable ASCII character), you can use "isalpha()", or "isalnum()" instead.
'Hope that helps!
Upvotes: 0