[英]What is the correct way of comparing two ASCII characters?
老實說,這是我作業的一部分問題。 但是,我確實盡了最大努力,但仍然沒有獲得預期的輸出。 所以我來這里尋求幫助。
現在,我需要對緩沖區中的單詞進行排序,以便它們以升序出現。 每個單詞都以空格作為分隔符結尾,並且空格不參與比較。
char *input = (char*) malloc(bufferSize*sizeof(char));
//這是包含來自stdin的單詞的緩沖區。
然后,我使用一個指針數組來存儲每個單詞的指針:
char **arrayPtr = (char**) malloc(numLines*sizeof(char*));
char *ptr = input;
for(int i = 0; i < numLines; i++){ //numLines is equal to number of words.
arrayPtr[i] = ptr;
while(*ptr != ' ')
ptr++;
ptr++;
}
之后,我調用qsort使用我自己的函數“ frobcmp”對單詞進行排序以進行比較。
qsort(arrayPtr, numLines, sizeof(char*), frobcmp);
int frobcmp(const void *a, const void *b){
const char *x = *(const char**)a;
const char *y = *(const char**)b;
while(1){
if(*x == ' ' && *y == ' ')
return 0;
else if(*x == ' ')
return -1;
else if(*y == ' ')
return 1;
int mask = 0x00101010;
int byteX = (int) *x;
int byteY = (int) *y;
int diff = (byteX ^ mask) - (byteY ^ mask);
if(diff) return diff;
x++;
y++;
}
}
我的問題是我的代碼有什么問題? 為什么結果輸出不是按升序排列的? 我的比較方法有問題嗎?
我真誠地期待有人提供幫助。如有必要,我可以附加更多代碼。
你有:
int mask = 0x00101010;
然后你說:
緩沖區中的這些字是雜亂無章的(與42進行XOR),因此在進行比較之前,我必須將這些字節恢復為原始狀態。
但是, 0x00101010
不是42
。 如果該數字是二進制數,則為42
但以十六進制表示。
您可以使用:
int mask = 42;
要么
int mask = 0x2A;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.