我如何把一个无符号的字符数组在C字符串? [英] How do I convert an unsigned char array into a string in C?

查看:391
本文介绍了我如何把一个无符号的字符数组在C字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个数组像这样

If I have an array such as this

unsigned char data[2850] = "";

通过我的计划的一部分运行后,最终将字节的元素,这样,如果通过它我环路和日志吧,我会看到下面的

that after running through a part of my program will eventually be full of byte elements such that if I loop through it and log it out I will see the following

    for (size_t i= 0; i < sizeof(data); i++) {
        printf("%02X ", data[i]);
    }

    //log window shows 01 24 81 00 0E 1C 44 etc...

有没有办法采取数据阵列的所有元素,并把它们放到一个const char?或者只是一个大字符串?但愿我是清楚。我的目标是最终把这个数据数组的所有元素融入一个base64连接codeD字符串,我可以在哪里在程序中使用别的。

Is there a way to take all the elements of the data array and put them into a const char? Or just one large string? Hopefully I'm being clear enough. My goal is to eventually turn all the elements of this data array into a base64 encoded string that I can use else where in the program.

推荐答案

一个字符串(char数组)的C为字符 S按一个sentianal字符终止的序贯序列(空终结:'\\ 0'

A string (char array) in C is a sequencial sequence of chars terminated by a sentianal character (the null terminator: '\0')

这意味着,如果你有值为0x00阵列中的任何地方的一个字节,它正是如此终止字符串潜在序列结束前。在您的例子,如果你转换你的数据数组转换成字符串它的结束将是第一个元素:

This means that if you have a byte of the value 0x00 anywhere in your array, it has thusly terminated the "string" potentially before the end of the sequence. In your example if you converted your data array into a string the end of it would be the first element:

data[]{00, EB, 23, EC, FF, etc... };

现在,如果你想使一个串出在这里的数据值,你可以做到这一点与的sprintf(),例如:

Now if you want to make a string out of the values of the data in here, you can do that with sprintf(), for example:

unsigned char val = 00;
data[0] = val;
char dump[5] = {0};

sprintf(dump, "%02x", data[0]);

现在你有它的值为00的字符串,你可以像使其fancer:

Now you have a string with the value "00" in it, You can make it fancer with something like:

sprintf(dump, "0x%02x", data[0]);

因此​​,该公司已经为0x00,以炫耀为十六进制数据。

So that it has "0x00" to show it off as hex data.

您可以循环像这样给满弦......但是请记住,可打印字符串需要至少2倍+ 1数据串的大小(2个为ASCII和+1为空)你必须填写步骤新的字符串。例如:

You could loop something like this to give the full string... but keep in mind that the printable string needs to be at least 2x+1 the size of the data string (2x for ASCII and +1 for null), and you have to fill the new string in steps. Example:

unsigned char data[5] = {0x00, 0x12, 0xB3, 0xFF, 0xF0};
char printstr[11] = {00};

for(int x = 0; x < 5; x++)
    sprintf(printstr+(x*2), "%02x", data[x]);
printstr[10] = '\0';

现在 printstr 0012b3fff0

这篇关于我如何把一个无符号的字符数组在C字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆