簡體   English   中英

在 C 中將字符串十六進制轉換為無符號字符 (BYTE)

[英]Converting string hexadecmials to unsigned char (BYTE) in C

我想將十六進制字符串值0x1B6轉換為unsigned char - 它將以0x1B0x60格式存儲值我們已經實現了 C++ 中的場景,但是 C 不支持std::stringstream

以下代碼是 C++,如何在 C 中實現類似的行為?

char byte[2];
std::string hexa;
std::string str = "0x1B6" // directly assigned the char* value in to string here 
int index =0;
unsigned int i;

for(i = 2; i < str.length(); i++) {
    hexa = "0x"

    if(str[i + 1] !NULL) {
        hexa = hexa + str[i] + str[i + 1];
        short temp;

        std::istringstream(hexa) >> std::hex >> temp;
        byte[index] = static_cast<BYTE>(temp);
    } else {
        hexa = hexa+ str[i] + "0";
        short temp;
        std::istringstream(hexa) >> std::hex >> temp;
        byte[index] = static_cast<BYTE>(temp);
    }
}
output:
byte[0] --> 0x1B
byte[1]-->  0x60

我認為您的解決方案效率不高。 但不管這一點,使用 C 你會使用strtol 這是如何實現類似目標的示例:

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

int main(void) {
    const char *hex_string = "0x1B60";
    long hex_as_long = strtol(hex_string, NULL, 16);
    printf("%lx\n", hex_as_long);

    // From right to left
    for(int i = 0; i < strlen(&hex_string[2]); i += 2) {
        printf("%x\n", (hex_as_long >> (i * 4)) & 0xff);
    }

    printf("---\n");

    // From left to right
    for(int i = strlen(&hex_string[2]) - 2; i >= 0; i -= 2) {
        printf("%x\n", (hex_as_long >> (i * 4)) & 0xff);
    }
}

所以在這里我們得到完整的值作為hex_as_long內部的long 然后,我們使用第一個 print 和第二個 for 循環內的單個字節打印整個 long。 我們正在移動 4 位的倍數,因為一個十六進制數字 ( 0xf ) 恰好覆蓋了 4 位數據。

要將字節或長字節打印到字符串而不是標准輸出(如果這是您想要實現的),您可以使用strprintfstrnprintf以類似於使用printf的方式,但使用變量或數組作為目標.

此解決方案一次掃描整個字節( 0xff )。 如果您需要一次處理一個十六進制數字( 0xf ),您可以將所有操作除以 2 並使用0xf而不是0xff進行掩碼。

暫無
暫無

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

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