I have the following problem when using memcpy:
Suppose that an hexadecimal data must be copied in binary, e.g.: 203800000E820006, then apply the following instruction:
unsigned char buffer[8];
memcpy(buffer,"\x20\x38\x00\x00\x0E\x82\x00\x06",8);
However, when I write the data in binary, it only prints the 2 first bytes in binary, because \x00 is interpreted as a string terminator. How to avoid or fix this in order to represent the 16-char string in a 8-char binary format?
The buffer you have is not a string. You can't treat it like one by passing it to functions expecting a string such as strcat, strcpy, strcmp, or the %s format specifier of printf.
You have an array of characters, so print them as such:
int i;
for (i=0;i<sizeof(buffer);i++) {
printf("%02hhX ", buffer[i]);
}
printf("\n");
Related
I'm starting with C, I have found a little difference between %c and %s, when must print special characters. I dont know if I'm doing something wrong, or it's a C limitation:
unsigned char str1[]="á";
printf("str1 c (%c)\n", str1[0]);
printf("str1 s (%s)\n", &str1[0]);
unsigned char str2[]="áéíóúñ";
printf("str2 s (%s)\n", str2);
And the output is:
str1 c ( )
str1 s (á)
str2 s (áéíóúñ)
In conclusion: when I try write special characters with %c, I cannot see it.
The %c format string for printf causes the corresponding argument to be converted to and interpreted as an unsigned char. An unsigned char is 1 byte long. One byte from your non-ASCII string does not necessarily correspond to anything you would recognize as a character.
It is likely that your editor, which you used to place some representation of those strings into your source code, encodes the two strings with some Unicode encoding scheme. This SO answer has some information to get you started on dealing with Unicode in C.
The reason things work fine with the %s formatting string is that printf will just start dumping out bytes until it hits the null byte terminator. Your output terminal is probably set to the same encoding scheme as your editor, so it's able to correctly interpret those bytes the way you intended.
Ok, now I understand it.
If I write:
unsigned char str3[]="a";
printf("%d\n", strlen((char *)str3));
The output is:
1
But I write:
unsigned char str1[]="á";
printf("%d\n", strlen((char *)str1));
The output is:
2
I understood that the character sizes can be 1, or 2 if are special characters , no?
I need to solve the following exercise:
"Write a program that acquires the first characters of a string an integer octal and write it on another string previously empty, then display the contents of this second string in decimal, using the functions sscanf and sprintf.
For example, if the user enters 12 (octal) the system must show 10 (decimal)."
After my scanf, the array seconda is ="12325".
The problem is that I do not know how to make understand that this string is an octal number and how to convert it to decimal with sprintf.
This is my current code:
#include <stdio.h>
int main(void) {
char prima[] = "12325dsdfa";
char secodna[500];
sscanf_s(prima, "%[0123456789]o", secodna, 500);
}
You're mis-using %o, mixing it with the character set format %[] and also passing too many arguments.
You should just use %o, it will convert an unsigned integer octal for as many characters as possible.
Then convert back to decimal string using %u with sprintf().
Something like this:
#include <stdio.h>
int main(void) {
unsigned int x;
if(sscanf("12foo", "%o", &x) == 1)
printf("%u\n", x);
return 0;
}
Note that the above outputs the decimal string to stdout rather than keeping it around (i.e. it uses printf() instead of sprintf()), but that's trivial to change. It prints "10".
Once it has been converted to a binary integer variable (with sscanf()) use sprintf() with a %u format to output it to the appropriate string.
Make sure you have the appropriate buffers defined first.
sscanf reference
sprintf reference
unsigned int intbuf;
char myinput[80];
char myoutput[80];
strcpy(myinput, "12345");
sscanf(myinput, "%o", &intbuf);
sprintf(myoutput, "%u", intbuf);
I have a function that returns a unsigned char chMAC[6]; which is the mac address and i print it out as
printf("Mac: %x",chMAC[0]);
printf("%x",chMAC[1]);
printf("%x",chMAC[2]);
printf("%x",chMAC[3]);
printf("%x",chMAC[4]);
printf("%x\n",chMAC[5]);
And i get an output as Mac: B827E82D398E which is the actual mac address, but now i need to get that value as a string to pass to a sql parameter and i don't know how, since i need to add : in between. such as Mac: B8:27:E8:2D:39:8E
i bet this is easy, but i am still learning C.
You probably want all the bytes to be displayed as two characters:
%2x
but with a leading 0 instead of space:
%02x
You can string this all together in one printf call
printf("Mac: %02X:%02X:%02X:%02X:%02X:%02X\n"
, chMAC[0], chMAC[1], chMAC[2], chMAC[3], chMAC[4], chMAC[5]);
If you want the text to go to a sting buffer instead of stdout do this:
char buffer[32];
snprintf(buffer, sizeof(buffer)
, "Mac: %02X:%02X:%02X:%02X:%02X:%02X\n"
, chMAC[0], chMAC[1], chMAC[2], chMAC[3], chMAC[4], chMAC[5]);
You have all the pieces there, you just need to string them into the right order. Instead of using 6 separate printf() statements, pull it into one statement with all the formatting:
printf("Mac: %02X:%02X:%02X:%02X:%02X:%02X\n",
chMAC[0], chMAC[1], chMAC[2], chMAC[3], chMAC[4], chMAC[5]);
The "02" in the "%02X" formatting statements will put a leading zero if the value is <15; the capital X will make the alphabetic Hex digits into capitals (which is the usual convention when passing MAC addresses).
To send the resulting string to a buffer instead of to stdout, call sprintf (or even better, snprintf) with the same formatting string.
char mac_str[24];
snprintf(mac_str, sizeof(mac_str), "Mac: %02X:%02X:%02X:%02X:%02X:%02X\n",
chMAC[0], chMAC[1], chMAC[2], chMAC[3], chMAC[4], chMAC[5]);
why all the separate calls?
newlength = sprintf(mac, '%x:%x:%x:%x:%x:%x\n', chMAC[1], etc....)
You can have multiple %whatever format characters in a single printf/sprintf call...
I have a struct that contains a string and a length:
typedef struct string {
char* data;
size_t len;
} string_t;
Which is all fine and dandy. But, I want to be able to output the contents of this struct using a printf-like function. data may not have a nul terminator (or have it in the wrong place), so I can't just use %s. But the %.*s specifier requires an int, while I have a size_t.
So the question now is, how can I output the string using printf?
Assuming that your string doesn't have any embedded NUL characters in it, you can use the %.*s specifier after casting the size_t to an int:
string_t *s = ...;
printf("The string is: %.*s\n", (int)s->len, s->data);
That's also assuming that your string length is less than INT_MAX. If you have a string longer than INT_MAX, then you have other problems (it will take quite a while to print out 2 billion characters, for one thing).
A simple solution would just be to use unformatted output:
fwrite(x.data, 1, x.len, stdout);
This is actually bad form, since `fwrite` may not write everything, so it should be used in a loop;
for (size_t i, remaining = x.len;
remaining > 0 && (i = fwrite(x.data, 1, remaining, stdout)) > 0;
remaining -= i) {
}
(Edit: fwrite does indeed write the entire requested range on success; looping is not needed.)
Be sure that x.len is no larger than SIZE_T_MAX.
how can I output the string using printf?
In a single call? You can't in any meaningful way, since you say you might have null terminators in strange places. In general, if your buffer might contain unprintable characters, you'll need to figure out how you want to print (or not) those characters when outputting your string. Write a loop, test each character, and print it (or not) as your logic dictates.
I am trying to copy the memory value of int into the char buffer. The code looks like below,
#define CPYINT(a, b) memcpy(a, &b, 4)
............
char str1[4];
int i = 1;
CPYINT(str1, i);
printf("%s",s);
...........
When I print str1 it’s blank. Please clarify.
You are copying the byte representation of an integer into a char array. You then ask printf to interpret this array as a null terminating string : str1[0] being zero, you are essentially printing an empty string (I'm skipping the endianness talk here).
What did you expect ? Obviously, if you wanted to print a textual representation of the integer i, you should use printf("%d", i).
try
printf("%02X %02X %02X %02X\n", str1[0], str1[1], str1[2], str1[3]);
instead.
The binary representation of the integer 1, probably contains leading NULs, and so your current printf statement terminates earlier than you want.
What is your intention here? Right now you are putting arbitrary byte values into the char array, but then interpreting them as a string, as it happens the first byte is probably a zero (null) and hence your print nothing, but in all probability many of the characters will be unprintable, so printf is the wrong tool to use to check if the copy worked.
So, either: loop through the array and print the numeric value of each byte, %0xd might be useful for that or if your intention is actually to create a string representation of the int then you'll need a larger buffer, and space for a null terminator.
Maybe you need convert intger to char* in that way tou can use itoa function
link text