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

后端 未结 4 1961
予麋鹿
予麋鹿 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:00

    In a 24-bit number bit #7 (counting from the left, as you did in your example, not from the right, as is done conventionally) is always going to be in the second byte from the left. You can solve your problem without converting the entire number to integer by taking that second hex digit, converting it to a number 0..15, setting its bit #3 (again counting from the left), and converting the result back to a hex digit.

    int fromHex(char c) {
        c = toupper(c);
        if (c >= '0' && c <= '9') {
            return c-'0';
        } else {
            return c-'A'+10;
        }
    }
    char toHexDigit(int n) {
        return n < 10 ? '0'+n : 'A'+n-10;
    }
    
    char myNum[] = "002A05";
    myNum[1] = toHexDigit(fromHex(myNum[1]) | 2);
    printf("%s\n", myNum);
    

    This prints '022A05' (link to ideone).

    0 讨论(0)
  • 2021-01-21 17:12

    You asked about strtol specifically, so to answer your question, just add padding after you convert the number with strtol:

    const char *s = "002A05";
    int x = strtol(s, NULL, 16);
    x |= (1<<17);
    printf("%.6X\n",x);
    
    0 讨论(0)
  • 2021-01-21 17:16
    int hex=0x002A05;
    int mask = 0x020000;
    printf ("%06X",hex | mask);
    

    hope this helps

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题