[英]Convert 20 Byte Hex (char string) to 10 Byte Binary Char String in C
我存儲了以下字符串。 1-F 為 16 字節,最后為 4 個空字節。
e.g. 1234567890ABCDEF0000
unsigned char input[] = {0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x00, 0x00, 0x00, 0x00};
我如何獲得這個 10 字節的二進制文件?
編輯:
我正在嘗試正確使用 openssl 加密庫的 SHA1 函數。 我的任務是從命令行讀取“鹽”和“密碼”。
然后把它們加在一起,這樣我就有了“鹽”+“|” +“密碼”。
如果沒有傳遞鹽,鹽只是“\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0”,即 10 個字節,對嗎? 但如果通過了鹽,它可能是“1234567890ABCDEF”
然后我必須用空字節填充它的右邊,這樣我總共有 10 個字節但是“1234567890ABCDEF”已經是 16 個字節,所以我必須轉換它。 我不知道,我真的在為 c 中的內存部分而苦苦掙扎
最簡單的可能是:
創建一個 0 初始化的 10 字節數組:
unsigned char salt[10] = { 0 };
然后使用sscanf()
逐字節讀取十六進制數字:
sscanf(input, "%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx",
&salt[0], &salt[1], &salt[2], &salt[3], &salt[4],
&salt[5], &salt[6], &salt[7], &salt[8], &salt[9]);
這將根據需要轉換盡可能多的字節; 如果只給出 6 個十六進制數字作為鹽,則前三個字節被填充,其余的保持為 0。
這應該符合您的預期。
嘿,我沒有從你的例子中得到太多,但是你描述的波紋管+約束可以這樣解決。 見片段。
如果沒有傳遞鹽,鹽只是“\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0”,即 10 個字節,對嗎? 但如果通過了鹽,它可能是“1234567890ABCDEF”
#include <stdio.h>
#include <string.h>
#define SALT_MAX_BYTES 10
int main(int argc, char *argv[]) {
// Init the whole array with 0-s, which is the same value as '\0'
char salt[SALT_MAX_BYTES] = {0};
// Here get the input, now assuming ./a.out [salt]
if (argc > 1) // The executable name is always passed
{
printf("Input: %s\n", argv[1]);
// Assuming ASCII...
// Assuming you want to use the ASCII value representation of input "42"
// and not the number 42 ...
strncpy(salt, argv[1], SALT_MAX_BYTES);
// Note: from here on you must strictly handle salt as length terminated.
// => input may have more then SALT_MAX_BYTES
}
else
{
puts("Usage: ...");
return -1;
}
// Left aligned output, showing nothing for \0 bytes...
printf("Entered salt is : <%-*.*s>\n", SALT_MAX_BYTES, SALT_MAX_BYTES, salt);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.