Frage

I want to print the hex value from a buffer.

message1 = calloc(1, sizeof(Message01_t));
    message1->number= clientNumber;
    char    buffer[BUFFERSIZE];
    size_t  bufferLen = sizeof(buffer); 
    der_encode_to_buffer(&asn_DEF_Message01, message1, buffer, bufferLen);
    xer_fprint(stdout, &asn_DEF_Message01, message1);
    for(j=0; j<sizeof buffer ; j++)
      printf("%02x ", buffer[j]);

if I change sizeof buffer to 5 I will get the result I except but with this code I get something like

Enter a number :
  4
<Message01>
    <number>4</number>
</Message01>
30 03 02 01 04 00 00 00 00 00 00 00 00 00 00 00 00 00 ......... A LOT OF ZEROS
War es hilfreich?

Lösung

First off, you have BUFFERSIZE implying that it is a global. You can make the length this as well and it will be the same size.

If you are looking for variable lengths in the response, you will need to use strlen()

size_t strlen(const char *s);

The strlen() function computes the number of bytes in the string to which s points, not including the terminating null byte. The strlen() function returns the length of s; no return value is reserved to indicate an error.

This is assuming that there is a null terminator '\0' that you received from or with your input. In the case of strings with c, the following string "Hi" can be see as a char array {'H', 'i', '\0'}. If you do not have the null terminator, then I am not sure how to handle varying lengths unless there is a return value or int you can set with a function.

Edit

Additionally, if you are looking for the hex value of a char or an int is also important as they are not the same. In your example, the user input "4" and you are presenting the hex value of the character '4' and then the null terminator '\0'. If you are wanting to present the hex value of the number 4 then you need to convert the string to an integer with:

int atoi(const char *str);

or:

(int) strtol(str, (char **)NULL, 10);

Then you can display the hex value for the number. This is assuming that the information provided by the user is an integer value. If it is not expected to be, then just looking at the string is probably your best bet.

Andere Tipps

Remember that the compiler will replace sizeof buffer by the array length in bytes, BUFFERSIZE in your case. Thus

for(j=0; j<sizeof buffer ; j++)

won't do what you expect but will always be equal to

for(j=0; j<BUFERSIZE; j++)

and that's where the garbage values (0x00 in your case) come from. That means you have to determine the 'real' buffer size at runtime. As I don't know the functions you're calling, I'm afraid I can't tell you how, strlen(), as @houckrj suggested works if (a) your buffer will never contain the value 0x00 and (b) der_encode_to_buffer() will terminate the buffer with '\0'. If you can't rely on that you will have to find another way.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top