我正在尝试理解二进制和十六进制数字。我想知道为什么我的程序不会在eclipse中启动。它给了我这个错误:
launch has encountered a problem
当我使用int
时,它正在运行。我的电脑是64位。我正在努力了解硬件。我需要知道我做错了什么。我可以改进什么?将缓冲区声明为全局变量是否可以?感谢。
我的代码在这里。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * convertBase(unsigned long int numberToConvert, long int base)
{
char buffer[65];
char *pConvertedNumber;
char allValues[] = "0123456789abcdef";
pConvertedNumber = &buffer[sizeof(buffer)-1];
*pConvertedNumber = '\0';
do {
int value = numberToConvert % base;
pConvertedNumber = pConvertedNumber - 1;
*pConvertedNumber = allValues[value];
numberToConvert /= base;
} while(numberToConvert != 0);
printf("%s", pConvertedNumber);
return pConvertedNumber;
}
int main(void){
unsigned long int numberOne = 1000000000;
printf("\n%ld in Base 16 = ", numberOne);
convertBase(numberOne, 16);
printf("\n");
return 0;
}
答案 0 :(得分:0)
或者您可以使用sprintf(缓冲区,&#34;%x&#34;,numbertoConvert),其中基数为16.但是,如果基数不是八进制或十六进制,则以下例程将起作用。
编辑请注意,这仅限于小于16的基数,ABCDF定义与十六进制相同(基数可以是11,12,13,14或15)。转换仍然正确。
编辑我还可以将基本字符列表更改为字符串数组并使用strcat,但我会将其留给您。 allValues [] = {&#34; 0&#34;,&#34; 1&#34;,...} strcat(buffer,allValues [value]);
您正在尝试打印缓冲区(如%s)而没有任何&#39; \ 0&#39;这意味着它没有被终止。代码应该是
size_t processBase(int numberToConvert, int base, char* mybuffer)
{
size_t mysize = 0;
mybuffer[0] = '\0';
if (base > 16 || base < 2)
{
printf("Invalid base specified\n");
return mysize;
}
switch(base)
{
case 16:
{
sprintf(mybuffer, "%#x", numberToConvert);
break;
}
case 8:
{
sprintf(mybuffer, "%#o", numberToConvert);
break;
}
case 10:
{
sprintf(mybuffer, "%d", numberToConvert);
break;
}
default:
{
convertBase(numberToConvert, base, mybuffer);
break;
}
}
printf("%s\n", mybuffer);
mysize = strlen(mybuffer);
return mysize;
}
void convertBase(int numbertoConvert, int base, char *rbuffer)
{
char buffer[65];
char *pConvertedNumber;
char allValues[] = "0123456789abcdef";
size_t mysize;
buffer[0] = '\0'; // This initializes the buffer
pConvertedNumber = &buffer;
do {
int value = numberToConvert % base;
*pConvertedNumber = allValues[value];
pconvertedNumber += 1;
*pconvertedNumber = '\0';
numberToConvert /= base;
} while(numberToConvert != 0);
mysize = strlen(buffer); // This shows the number of characters
for (int i = 1; i <= mysize; i++)
{
rbuffer[mysize-i] = buffer[i-1];
}
rbuffer[mysize] = '\0';
}
int main(void)
{
unsigned long int numberOne = 1000000000;
int base = 12
mybuffer[65];
printf("\n%ld in Base %d = ", numberOne, base);
size_t mysize = processBase(numberOne, base, mybuffer);
printf("Has %d characters\n", mysize);
return 0;
}
答案 1 :(得分:0)
..或没有字符串反转,并且调用者提供缓冲区:
#include <stdio.h>
const char* hexlat="0123456789ABCDEF";
char * convertBase(unsigned long int numberToConvert, int base, char *output){
if(numberToConvert>base) output=convertBase(numberToConvert/base,base,output);
*output=hexlat[numberToConvert % base];
return output+1;
};
int main(void) {
unsigned int numToConvert=1000000000;
char ascResult[64];
*convertBase(numToConvert,16,ascResult)='\0';
printf("%s",ascResult);
return 0;
}