簡體   English   中英

f1()函數將如何執行?

[英]How this function f1() will execute?

#include <stdio.h>
void f1(char* str, int index)
{
   *(str + index) &= ~32;
}
int main()
{
   char arr[] = "gatecsit";
   f1(arr, 0);
   printf("%s", arr);
   return 0;
}

函數f1()如何工作?
是特定的*(str + index)&=〜32; 這個...。謝謝

我認為f1()通過利用ASCII的屬性將字符串的第一個字母大寫,這意味着相應的小寫和大寫字母相差32。例如,“ A”的代碼為65,而“ a”的代碼為97.該代碼的“&=〜32”位將把字符str [index]的ASCII表示的第5位變為“ g”。 這對於只包含普通字母的字符串應該是正確的,但是會對數字和標點符號產生奇怪的影響。

表達方式

*(str + index)

相當於

str[index]

因此,位置index處的字符按以下方式更改

*(str + index) &= ~32;

在ASCII表中,小寫字母與大寫字母的不同之處是多了一個設置位。 例如,小寫字母'a'具有十六進制61的代碼,而大寫字母'A"具有十六進制41的代碼,因此,該差等於十六進制20中的值,十進制等於32

因此,原始表達式會將字符中的相應位重置為0,從而將小寫字母轉換為大寫字母。

該代碼從字符中刪除了1位,從字節或0x20有效減去32。

#include <stdio.h>
#include <string.h>

void f1(char* str, int index)
{
 // The code removes 1 bit from the character at the position `str[index]`
 // effectively subtracting 32 from that character
 // Capital letters in ASCII are apart by 32 (0x20) from small letters 

 // Since 'a' = 0x61 and 'A' = 0x41  'a' - 32 = 'A'
 // Since 'b' = 0x62 and 'B' = 0x42  'b' - 32 = 'B'

 // `~` is a binary negation operator 0 -> 1;  1 -> 0
 // `&` is a binary AND
 // x &= y; is equivalent to x = x & y;

 // ~0x20 = 0b11011111    

   *(str + index) &= ~0x20; // 0x20 = 32;
}


int main()
{
   int i;
   char arr[] = "gatecsit";
   size_t len = strlen(arr);


  for(i = 0; i< len; i++)
      printf(" %c " , arr[i]);   

   printf("\n");

  for(i = 0; i< len; i++)
      printf(" %X" , arr[i]);

   printf("\n");

  // convert all letters:  
   for(i = 0; i< len; i++)
      f1(arr, i);

   printf("\n");

  for(i = 0; i< len; i++)
      printf(" %c " , arr[i]);  

   printf("\n");

  for(i = 0; i< len; i++)
      printf(" %X" , arr[i]);

   return 0;
 }

輸出:小寫字母和大寫字母相隔0x20(或32個十進制)。 從此打印輸出可以清楚地看到:

 g  a  t  e  c  s  i  t 
 67 61 74 65 63 73 69 74

 G  A  T  E  C  S  I  T 
 47 41 54 45 43 53 49 54

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM