Reputation:
I had such code
char *p = "\xFF\xFF\xFF\xFF\xFF\xFF";
for(int i = 0; i<6; i++)
printf(" %d ", *(p + i));
But the output was -1 -1 -1 -1 -1 -1, which is not what I want. I wanted 255 255 255 255 255 255.
So, I modified above code like this:
unsigned char *p = "\xFF\xFF\xFF\xFF\xFF\xFF";
for(int i = 0; i<6; i++)
printf(" %d ", *(p + i));
But was getting error: "a value of type "const char *"
cannot be used to initialize an entity of type "unsigned char *"
Finally, I modified it like this and it works.
unsigned char *p = (unsigned char*) "\xFF\xFF\xFF\xFF\xFF\xFF";
for(int i = 0; i<6; i++)
printf(" %d ", *(p + i));
I think this is a fine modification, right?
Upvotes: 2
Views: 709
Reputation: 2909
The type of the string literal "\xFF\xFF\xFF\xFF\xFF\xFF"
is const char*
. Without having to use dirty casting to non-const type you should declare p
as const
:
const char *p = "\xFF\xFF\xFF\xFF\xFF\xFF";
If you then want to output as unsigned values, cast the values in your output line.
for(int i = 0; i<6; i++)
printf(" %u ", (unsigned char)(*(p + i)));
Background: The literal is safed in a possibly read-only area of your memory (while this is not the fact on usual pc systems, where the memory is writable). You should yet not depend on the memory to be writeable and if you don't so, you may declare the data const
.
Upvotes: 0
Reputation: 7204
It is better to use numbers when printing numbers and strings when printing strings. So:
unsigned char p[6];
memset(p, 0xFF, 6);
for(int i = 0; i<6; i++)
printf(" %d ", p[i]);
Edit: Just to know. If the most significant bit is 1 then it is negative, if you declair char or int or short so 255 = 0b**1**1111111
negative
valter
Upvotes: 1
Reputation: 9395
Use
for(int i = 0; i<6; i++)
printf(" %u ", (unsigned char)(*(p + i)));
To print.
Upvotes: 1