[英]How to convert char 'G' to string “47” (hex)
我想從標准輸入讀取一個字符串,將其保存在一個數組中,進行轉換,使其與指定的測試相匹配:
expected = "45 76 65 72 79 20"
自星期五以來,我已經嘗試了所有我能找到的解決方案,除了我不明白如何使用的strtol
。
char input;
char *buffer = NULL;
char chunk[2];
size_t stringLength = 0;
int n = 0;
while(fgets(chunk, 2, stdin) != NULL){
stringLength += strlen(chunk);
}
rewind(stdin);
buffer = (char *) malloc(stringLength + 1);
if (buffer == NULL)
exit(EXIT_FAILURE);
while(scanf("%c", &input) == 1) {
snprintf(buffer+n, 2, "%c", input);
n += strlen(chunk);
}
//code to convert char array buffer to array of hex separated by spaces
從 stdin = "Every P";
字符串我需要 output 才能通過示例測試: = "45 76 65 72 79 20 50";
如果我犯了任何錯誤,請告訴我,我已經學習如何編寫 C 代碼 1 1/2 個月了。
提前致謝!
AFAIK, rewind(stdin)
是有問題的。 另一種選擇是使用realloc
一次增加一個字符的數組。
int c;
char *s = NULL;
int char_count = 0;
// Read one char at a time, ignoring new line
while (EOF != (c = getc(stdin))) {
// Ignore CR (i.e. Windows)
if ('\r' == c) continue;
// Consume the newline but don't add to buffer
if ('\n' == c) break;
// Grow array by 1 char (acts like malloc if pointer is NULL)
s = realloc(s, ++char_count);
// TODO handle error if (s == NULL)
// Append to array
s[char_count - 1] = (char)c;
}
// Create the buffer for the hex string
// 3 chars for each letter -> 2 chars for hex + 1 for space
// First one does not get a space but we can use the extra +1 for \0
char *hex = malloc(char_count * 3);
// TODO handle error if (hex == NULL)
// Create a temporary pointer that we can increment while "hex" remains unchanged
char *temp = hex;
for (int i = 0; i < char_count; i++) {
// No space on first char
if (i == 0) {
sprintf(temp, "%02X", s[i]);
temp += 2;
}
else {
sprintf(temp, " %02X", s[i]);
temp += 3;
}
}
*temp = '\0';
printf("%s\n", hex);
// Cleanup
free(s);
free(hex);
輸入: Every P
Output: 45 76 65 72 79 20 50
如果您只想將stdin
重新打印為十六進制,則根本不需要任何緩沖區:
int c;
int char_count = 0;
// Read one char at a time and print as hex
while (EOF != (c = getc(stdin))) {
// No space on first char
if (0 == char_count++) {
printf("%02X", c);
}
else {
printf(" %02X", c);
}
}
puts(""); // If you need a newline at the end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.