如何将一个无符号字符数组转换成在C十六进制字符串 [英] How to convert an Unsigned Character array into a hexadecimal string in C

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

问题描述

是否有可能重新present一个无符号字符数组作为字符串?

Is it possible to represent an unsigned character array as a string?

当我寻找,我发现,只有memset的()是能够做到这一点(不过逐个字符)。
假设是不正确的做法,有没有办法做转换?

When I searched for it, I found out that only memset() was able to do this (But character by character). Assuming that is not the correct way, is there a way to do the conversion?

上下文:我想保存这恰好是无符号的字符数组的加密散列函数的输出结果。
例如:

Context: I am trying to store the output of a cryptographic hash function which happens to be an array of unsigned characters.
eg:

unsigned char data[N]; ...
for(i=0;i<N;i++) printf("%x",data[i]);

我的目标是重新present数据作为一个String(%S),而不是由每个元素访问它。因为我需要的散列值的输出作进一步处理的字符串。

My goal is to represent the data as a String (%s) rather than access it by each element. Since I need the output of the hash as a String for further processing.

谢谢!

推荐答案

因此​​,基于您的更新,你在说什么想一个无符号的字符缓冲区转换为十六进制间pretation,是这样的:

So, based on your update, are you talking about trying to convert a unsigned char buffer into a hexadecimal interpretation, something like this:

#define bufferSize 10
int main() {
  unsigned char buffer[bufferSize]={1,2,3,4,5,6,7,8,9,10};
  char converted[bufferSize*2 + 1];
  int i;

  for(i=0;i<bufferSize;i++) {
    sprintf(&converted[i*2], "%02X", buffer[i]);

    /* equivalent using snprintf, notice len field keeps reducing
       with each pass, to prevent overruns

    snprintf(&converted[i*2], sizeof(converted)-(i*2),"%02X", buffer[i]);
    */

  }
  printf("%s\n", converted);

  return 0;
}

它输出:

0102030405060708090A

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

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