Change bit of hex number with leading zeros in C++,(C)

后端 未结 4 1966
予麋鹿
予麋鹿 2021-01-21 16:24

I have this number in hex string:

002A05.

I need to set 7-th bit of this number to 1, so after conversion I will get

022A05
         


        
4条回答
  •  孤街浪徒
    2021-01-21 17:19

    It sounds to me like you have a string, not a hex constant, that you want to manipulate. You can do it pretty easily by bit twiddling the ascii value of the hex character. If you have char representing a hex character like char h = '6';, char h = 'C';, or char h = '';, you can set the 3rd from the left (2nd from the right) bit in the number that the character represents using:

     h = h > '7' ? h <= '9' ? h + 9 : ((h + 1) | 2) - 1 : h | 2;
    

    So you can do this to the second character (4 + 3 bits) in your string. This works for any hex string with 2 or more characters. Here is your example:

    char hex_string[] = "002A05";
    
    // Get the second character from the string
    char h = hex_string[1];
    
    // Calculate the new character
    h = h > '7' ? h <= '9' ? h + 9 : ((h + 1) | 2) - 1 : h | 2;
    
    // Set the second character in the string to the result
    hex_string[1] = h;
    
    printf("%s", hex_string); // 022A05
    

提交回复
热议问题