我正在制作一個作業系統并已啟動到用 c 制作的 64 位內核。我已經制作了一個正在作業的列印函式,并且正在嘗試制作一個將十六進制值轉換為字串的函式,以便我可以列印它們。我的代碼導致啟動回圈,但是當我編譯完全相同的代碼以在 linux 中正常運行時,它可以完美運行。相關代碼:
int logarithm(double value, int base, int* output) {
int i = 0;
while (value > 1) {
value /= base;
i ;
}
*output = i;
}
int power(int value, int power, int* output) {
if (power == 0) {
value = 1;
} else {
for (int i = 0; i < (power - 1); i ) {
value *= value;
}
}
*output = value;
}
void hexToStr(unsigned int hex, char** string) {
int hexLength = 0;
logarithm((double)hex, 16, &hexLength);
char output[hexLength];
output[hexLength] = 0;
int powerValue = 0;
for (int i = 0; i < hexLength; i ) {
power(16, i, &powerValue);
output[hexLength - i - 1] = (hex & (powerValue * 15)) / powerValue '0';
}
*string = output;
}
如果我將 hexToStr() 函式代碼更改為此(通過硬編碼字串值來消除對 logarithm() 和 power() 函式的需要),它在 linux 和我的內核中都有效:
void hexToStr(unsigned int hex, char** string) {
int hexLength = 10;
char output[hexLength];
output[hexLength] = 0;
int powerValue = 0;
for (int i = 0; i < hexLength; i ) {
output[hexLength - i - 1] = 'A';
}
*string = output;
}
關于為什么會發生這種情況的任何建議?
uj5u.com熱心網友回復:
呈現的代碼呼叫未定義的行為。例如讓我們考慮這個函式
void hexToStr(unsigned int hex, char** string) {
int hexLength = 10;
char output[hexLength];
output[hexLength] = 0;
int powerValue = 0;
for (int i = 0; i < hexLength; i ) {
output[hexLength - i - 1] = 'A';
}
*string = output;
}
在這個賦值陳述句中:
output[hexLength] = 0;
陣列外有寫入資料,因為索引的有效范圍是[0, hexLength).
或者該函式設定一個通過參考本地陣列傳遞給該函式的指標,該陣列output在退出函式后將不再存在。所以回傳的指標會有一個無效的值。
power另一個例子,當引數value等于3和引數power等于時,函式的結果值3將等于81而不是27由于這個for回圈中的賦值陳述句。
for (int i = 0; i < (power - 1); i ) {
value *= value;
}
此外,盡管它的回傳型別不是 void,但該函式什么也不回傳。
int power(int value, int power, int* output) {
還有這個表達
(hex & (powerValue * 15)) / powerValue '0'
沒有意義。
uj5u.com熱心網友回復:
需要啟用 SSE 單元才能使用浮點數和雙精度數。以及更改值的傳回方式。作業代碼:
void log(float value, float base, uint64_t* output) {
uint64_t i = 0;
while (value >= 1) {
value /= base;
i ;
}
*output = i;
}
void pow(uint64_t value, uint64_t exponent, uint64_t* output) {
uint64_t result = 1;
for (uint64_t i = 0; i < exponent; i ) {
result = result * value;
}
*output = result;
}
void hexToStr(uint64_t hex, char* output) {
uint8_t hexLen = 16;
log((float)hex, (float)16, &hexLen);
char result[hexLen 3];
result[0] = '0';
result[1] = 'x';
result[hexLen 2] = 0;
uint64_t powerValue = 1;
for (uint8_t i = 0; i < hexLen; i ) {
pow(16, i, &powerValue);
result[hexLen - i 1] = (hex & (uint64_t)(powerValue * (uint64_t)15)) / powerValue '0';
}
for (uint8_t i = 0; i < hexLen 3; i ) {
switch(result[i]) {
case ':':
result[i] = 'A';
break;
case ';':
result[i] = 'B';
break;
case '<':
result[i] = 'C';
break;
case '=':
result[i] = 'D';
break;
case '>':
result[i] = 'E';
break;
case '?':
result[i] = 'F';
break;
}
output[i] = result[i];
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/467869.html
下一篇:在頁面上居中引導網格
