[英]C programming Hex to Char
What I'm trying to do is have the user input a hex number this number will then be converted to a char and displayed to the monitor this will continue until an EOF
is encountered.I have the opposite of this code done which converts a char to a hex number. 我正在尝试做的是让用户输入一个十六进制数字,然后将该数字转换为字符,并显示在监视器上,直到遇到
EOF
为止。我执行了与转换字符相反的代码到十六进制数。 The problem I'm running into is how do i get a hex number from the user I used getchar()
for the char2hex
program. 我遇到的问题是如何从为
char2hex
程序使用getchar()
的用户获取十六进制数。 Is there any similar function for hex numbers? 十六进制数字有任何类似的功能吗?
this is the code for the char2hex program 这是char2hex程序的代码
#include <stdio.h>
int main(void) {
char myChar;
int counter = 0;
while (EOF != (myChar = getchar())) {
/* don't convert newline into hex */
if (myChar == '\n')
continue;
printf("%02x ", myChar);
if (counter > 18) {
printf("\n");
counter = -1;
}
counter++;
}
system("pause");
return 0;
}
this is what i want to the program to do except it would do this continuously 这是我要程序执行的操作,除非它会连续执行此操作
#include <stdio.h>
int main() {
char myChar;
printf("Enter any hex number: ");
scanf("%x", &myChar);
printf("Equivalent Char is: %c\n", myChar);
system("pause");
return 0;
}
any help would be appreciated thank you 任何帮助将不胜感激谢谢
Because chars and ints can be used interchangably in C, you can use the following code: 由于char和ints可以在C语言中互换使用,因此可以使用以下代码:
int main(void) {
int myChar;
printf("Enter any hex number: ");
scanf("%x", &myChar);
printf("Equivalent Char is: %c\n", myChar);
system("pause");
return 0;
}
If you want it to loop then just enclose it in the while loop as in your example code. 如果您想让它循环,则只需将其放入示例代码中的while循环中即可。
Edit: You can try out the working code here http://ideone.com/yyvz85 编辑:您可以在这里尝试工作代码http://ideone.com/yyvz85
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(void) {
int myChar;
int counter = 0;
char buff[3] = {0};
while (EOF != (myChar = getchar())) {
if(isxdigit(myChar)){
buff[counter++] = myChar;
if(counter == 2){
counter = 0;
myChar = strtol(buff, NULL, 16);
putchar(myChar);
}
}
}
printf("\n");
system("pause");
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.