C++中怎样把十六进制数据赋到字符串的内存?

如题所述

16进制数据仅是整数的一种表现形式,把十六进制数据赋到字符串的内存,就是把一个整数写到内存地址中,可采用的最简单的办法就是用memcpy()函数。

相关头文件:

#include <string.h>

函数原型:

void * memcpy( void *dest, void * src, size_t len );

dest:目标地址

src:数据源所在地址

len:拷贝的数据长度

功能:从数据源所在地址src开始,拷贝len个字节到dest地址中。

参考代码:

#include <stdio.h>
#include <string.h>
void main()
{
    int n=0x12345678 ;
    char str[10];
    memcpy( str, &n, sizeof(int) );
    for( int i=0;i<sizeof(int);i++ ) //输出显示n在内存中的存储情况,因机器不同,显示有可能不同(大小端机)
        printf("%x\n", str[i]&0xff );
}

运行结果:

小端机:

78

56

34

12

大端机:

12

34

56

78

温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-06-07
16进制数据?直接变量赋值
16进制的形式在字符串中显示?转换再赋值追问

直接变量赋值要怎么做?

追答

一楼的memcpy就可以
memcpy(目标数据区,源数据区,复制数据的长度);
memcpy(str_buf,src_data,nLength);
你看看这个:char str_buf[10]={0x43,0x2B,0x2B,0x00};
执行后,str_buf是"C++“

第2个回答  2012-06-02
unsigned long data = 0x12345678;
char buf[16];
sprintf(buf, "%#x", data);
std::string str;
str.append(buf); 或者 str.Format(...)
第3个回答  2012-06-01
memcpy
相似回答