[英]How to concatenate an hex to a string in C
I'm trying to create a string that's composed with multiple parts. 我正在尝试创建由多个部分组成的字符串。 It starts as a normal string and at some point a function is called that fills a pointer with an hex number.
它以普通字符串开头,并在某些时候调用一个函数,该函数用十六进制数字填充指针。 Like shown below.
如下图所示。
PVOID hexval = NULL;
PCTSTR mystring = TEXT("BLA");
function(&hexval);
mystring += hexval; // just an idea of what I want, not actual code
As shown above I want mystring
to have the hexvalue
appended to it. 如上所示,我希望
mystring
可以附加hexvalue
。 Assume my hexvalue
is 0x424C41
. 假设我的
hexvalue
值为0x424C41
。 I want to end with mystring
being "BLABLA". 我想以
mystring
作为“ BLABLA”结束。
What's the best way to do this? 最好的方法是什么?
(Assuming I understand you correctly, and that UNICODE is not define by the preprocessor) (假设我理解正确,并且预处理程序未定义UNICODE)
you should do the following: 您应该执行以下操作:
There are two tricky points here: 这里有两个棘手的问题:
hexval
directly. hexval
字节序计算机,则需要重新排序字节,而不能直接从hexval
复制。 HOWEVER! 然而! I advise you against doing any of this.
我建议您不要这样做。 It is much better to avoid getting into a situation in which you need to perform these brute-force conversions.
最好避免陷入需要执行这些蛮力转换的情况。 I would bet you could probably solve whatever problem you're facing differently.
我敢打赌,您可能会以不同的方式解决任何问题。
#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);
}
Maintaining ANSI-support in 2019 is masochism, though. 不过,在2019年保持ANSI支持是受虐狂。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.