0

I have this string.

char * data = "A1B2C3D4E5F6A7B8";

Here each A1 B2 C3 D4 E5 F6 A7 B8 will be bytes for unsigned char* buffer.

My concern is how to convert the data into unsigned char* buffer.

unsigned char* buffer;
buffer = (unsigned char*)data;

I will use the buffer for a parameter of a function like this to write the data into memory.

int abc(uint64_t address, buffer, uint32_t lenght);

Can anyone please give me a correct way?

7
  • char * data = "A1B2C3D4E5F6A7B8"; is not allowed. data must be const char*. What does buffer mean here? Do you allocate memory for it somewhere? Commented Oct 14, 2022 at 2:43
  • Yes I will allocate memory with the buffer. Commented Oct 14, 2022 at 2:44
  • But buffer now doesn't point to any allocated memory, it points to the string literal, after your edit of the question. Commented Oct 14, 2022 at 2:45
  • How can I convert char* buffer to unsigned char buffer seems apropos. Commented Oct 14, 2022 at 2:45
  • 1
    What does " convert the data into unsigned char* buffer" mean? Commented Oct 14, 2022 at 2:48

1 Answer 1

0

Here it is a demo about the char* buffer, unsigned char* and string.

// test.cpp
#include<iostream>
using namespace std;
void fun(unsigned char* pt) {
   cout<<*pt<<*(pt+1)<<endl;  // print first and second element
}
int main(){
    char Data[] = "abcde";       // a string with 6 elements stored in char array.
    char* data = Data;           // char pointer point to the char array
    unsigned char* buffer;       // declare an unsigned char
    buffer = (unsigned char*) data;  // buffer points to the same address data pointed.
    fun(buffer);                 // function requires an unsigned char pointer
    return 0;
}

The output

ab

To compile and run

g++ -Wall test.cpp;
./a.out

P.S.

char * data = "A1B2C3D4E5F6A7B8";

The above line would cause a warning when compiling because the string is immutable. Better changes it to char const * data = "A1B2C3D4E5F6A7B8";

Sign up to request clarification or add additional context in comments.

2 Comments

I like the -Wall part
Thanks for reply. but my actual concern is That A1 B2 is hexadecimal. if char * data is "0102" , it will be 0000000100000002 in binary.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.