[英]How to add 2 four bit Hexa to make a ASCII char byte
I have a binary file from a source, from which i have to retrive data so that it is read in human readable form. 我有一个来自源的二进制文件,我必须从中检索数据,以便以人类可读的形式读取数据。 I have retrived the data and have it in the 4 bit hexa.
我已检索数据并将其保存在4位六进制中。 For eg the file size is 256 byte and i am retrieving it in hexa and getting 512 4 bit hexa values.
例如,文件大小为256字节,而我正在以十六进制的形式获取它,并获得512个4位六进制值。 Now, to make it human readable ASCII chars, i have to add two 4 bit hexa to make a byte.
现在,要使其成为人类可读的ASCII字符,我必须添加两个4位六进制以构成一个字节。 The way i am retrieving the data in Hex format is
我以十六进制格式检索数据的方式是
byte = read_buffer[i];
// Convert the Most Significant nibble for first byte
write_buffer_hex[(i + 1) * 2 + 0] = hex_chars[(byte >> 4)];
// Convert the Least Significant nibble for the first byte
write_buffer_hex[(i + 1) * 2 + 1] = hex_chars[byte & 0x0f];
Now, my question is how should i add these two hex values to have a ASCII value. 现在,我的问题是我应该如何将这两个十六进制值相加以具有ASCII值。 The way i am doing now is to just add these two, but is it the correct way ??.
我现在要做的就是将这两个加在一起,但这是正确的方法吗? Thank you
谢谢
I agree with John, it may be easier to output it directly in the hexadecimal basis like so: 我同意约翰的观点,以十六进制为基础直接输出可能会更容易,例如:
printf("%x", byte);
or with C++'s IOstream library: 或使用C ++的IOstream库:
cout << hex << byte;
Use a lookup table: 使用查找表:
static char const alphabet[] = "0123456789ABCDEF";
// Loop:
output[cursor++] = alphabet[byte % 16];
output[cursor++] = alphabet[byte / 16];
You can index directly into the string, too: 您也可以直接在字符串中建立索引:
output[cursor++] = "0123456789ABCDEF"[byte % 16];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.