![](/img/trans.png)
[英]How to convert bitmap 16-bit RGBA4444 to 16-bit Grayscale in C++?
[英]How to convert an array of 16-bit values to base64?
所以我現在正在研究C ++中的加密/解密方法。 它以std::string
作為輸入(加上用於加密消息的“密鑰”),並生成代表加密字符串的std::string
輸出。
在加密過程中,我將std::string
轉換為uint16_t
數組,並在加密過程中對此進行了一些計算。 其中的原因很簡單,因為一個uint_16_t
值通過算法則給出了更凈空加密原始值char
一樣。
問題是,為了以std::string
返回加密的消息,我需要以某種方式將uint_16_t
值的數組轉換為可讀的內容(即適合char
數組的內容而不溢出)。 為此,我以為我可以使用base64,但是我發現的所有base64實現都只將std::string
或char*
作為輸入(8位/元素)。 顯然,如果我將其提供給uint16_t
數組,我將永遠無法找回原始值,因為base64函數會在轉換之前將其轉換為8位。
所以這是我的問題:有人知道將uint16_t
數組編碼為可打印的字符串(如base64)並返回而不會丟失任何數據的方法嗎?
我知道我必須獲取數據的字節才能使用base64,但是我不確定該怎么做。
感謝您的任何幫助!
您可以使用base-n微型庫,該庫提供基於迭代器的通用I / O。
以下代碼按預期方式將“ 1 2 3 4 65535”輸出到stdout:
uint16_t arr[] { 1, 2, 3, 4, 65535 };
const int len = sizeof(arr)/sizeof(arr[0]);
std::string encoded;
bn::encode_b64(arr, arr + len, std::back_inserter(encoded));
uint16_t out[len] { 0 };
bn::decode_b64(encoded.begin(), encoded.end(), out);
for (auto c : out) {
std::cout << c << " ";
}
強制性披露:我是圖書館的作者
假設uint16_t值的范圍從零到63,並且您使用的是ASCII,只需將0x21(十六進制21)添加到每個值並將其輸出。 這將創建一個可打印的字符串,但是出於顯示目的,您可能還希望在一定數量的字符后打印新行,而不是顯示一個很長的字符串。 任何解碼器都必須從從文件中讀取的每個字符中減去0x21(如果文件中有換行符,則將其忽略(在減去0x21之前進行此檢查))。
在此處查看上一個問題: c ++中的base64解碼代碼段
將uint16_t*
強制轉換為unsigned const char*
並進行編碼,如下所示:
// Data to base64 encode
std::vector<uint16_t> some_data;
// Populate some_data...
// ...
// base64 encode it
std::string base64_data = base64_encode((unsigned char const*)&some_data[0], some_data.size()*2 );
所以我終於解決了。 我發布它是為了防止其他人需要這樣的東西。 基本上,我將uint16_t
值分別分成兩個uint8_t
,並且由於它們是8位值,因此它們可以與任何base64實現一起使用。 這是我的方法:
#include <iostream>
using namespace std;
#define BYTE_T uint8_t
#define TWOBYTE_T uint16_t
#define LOWBYTE(x) ((BYTE_T)x)
#define HIGHBYTE(x) ((TWOBYTE_T)x >> 0x8)
#define BYTE_COMBINE(h, l) (((BYTE_T)h << 0x8) + (BYTE_T)l)
int main() {
// an array with 16-bit integers
uint16_t values[5] = {1, 2, 3, 4, 65535};
// split the 16-bit integers into an array of 8-bit ones
uint8_t split_values[10]; // notice that you need an array twice as big (16/8 = 2)
int val_count = 0;
for (int i=0; i<10; i+=2) {
split_values[i] = HIGHBYTE(values[val_count]);
split_values[i+1] = LOWBYTE(values[val_count]);
val_count++;
}
// base64 encode the 8-bit values, then decode them back
// or do whatever you want with them that requires 8-bit numbers
// then reunite the 8-bit integers to the original array of 16-bit ones
uint16_t restored[5];
int rest_count = 0;
for (int i=0; i<10; i+=2) {
restored[rest_count] = BYTE_COMBINE(split_values[i], split_values[i+1]);
rest_count++;
}
for (const auto &i : restored) cout << i << " ";
cout << endl;
return 0;
}
當然,相同的方法將適用於任何長度。 您只需要更改for循環的位即可。 可以輕松修改此代碼,以將32位int拆分為16位int或任何其他內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.