[英]How to concatenate an hex to a string in C
我正在尝试创建由多个部分组成的字符串。 它以普通字符串开头,并在某些时候调用一个函数,该函数用十六进制数字填充指针。 如下图所示。
PVOID hexval = NULL;
PCTSTR mystring = TEXT("BLA");
function(&hexval);
mystring += hexval; // just an idea of what I want, not actual code
如上所示,我希望mystring
可以附加hexvalue
。 假设我的hexvalue
值为0x424C41
。 我想以mystring
作为“ BLABLA”结束。
最好的方法是什么?
(假设我理解正确,并且预处理程序未定义UNICODE)
您应该执行以下操作:
这里有两个棘手的问题:
hexval
字节序计算机,则需要重新排序字节,而不能直接从hexval
复制。 然而! 我建议您不要这样做。 最好避免陷入需要执行这些蛮力转换的情况。 我敢打赌,您可能会以不同的方式解决任何问题。
#include <stddef.h>
#include <stdlib.h>
#include <windows.h>
#include <tchar.h>
int main(void)
{
ULONG_PTR value = 0x424C41;
LPVOID hexval = &value;
PCTSTR mystring = _T("BLA");
size_t length = _tcslen(mystring);
size_t new_size = length + sizeof(ULONG_PTR) + 1;
LPTSTR new_string = calloc(new_size, sizeof(*new_string));
_tcscpy(new_string, mystring);
size_t offset;
for (offset = sizeof(ULONG_PTR); offset && !((char*)hexval)[offset - 1]; --offset);
for (size_t i = length ? length : 0, k = offset; k; ++i, --k)
new_string[i] = ((char*)hexval)[k - 1];
_tprintf(_T("\"%s\"\n"), new_string);
free(new_string);
}
不过,在2019年保持ANSI支持是受虐狂。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.