简体   繁体   English

如何从c中的数组打印char类型?

[英]How do I print char types from an array in c?

int remainder;
char Hex[8];
int quotient, power;
remainder = (original_value*-1)-1;
for (int k = len; k > 0 ; k--)
{
    if (sign == 1)
    {
        power = pow(16, k-1);
        quotient = 15 - (remainder/power);
        remainder = remainder%power;
        if (quotient < 10)
            Hex[len - k] = (int)quotient;
        else if (quotient == 10)
            Hex[len - k] = 'A';
        else if (quotient == 11)
            Hex[len - k] = 'B';
        else if (quotient == 12)
            Hex[len - k] = 'C';
        else if (quotient == 13)
            Hex[len - k] = 'D';
        else if (quotient == 14)
            Hex[len - k] = 'E';
        else if (quotient == 15)
            Hex[len - k] = 'F';
    }
}


for(int k = 0; k < len; k++)
    printf("%s", Hex[k]);

I did not include the rest of the code, as this little bit should hopefully explain what I am trying to achieve. 我没有包括其余的代码,因为这应该可以解释我要实现的目标。 My goal is to print out a Base 16 representation of any number that is entered by a user, but I need to save this data into an array for later use, how do I print the data within my char array (The last two lines), such that the characters display as they do in my for loop? 我的目标是打印出用户输入的任何数字的Base 16表示形式,但是我需要将此数据保存到数组中以备后用,如何在char数组中打印数据(最后两行) ,以使字符像在我的for循环中一样显示?

try This hope this will work and enjoy 尝试这个希望这将工作并享受

  printf("%s", Hex[k]); ==> printf("%c", Hex[k]);

And pow to elevate a power of 2 is really sub-optimal. 而pow提升2的幂实际上是次优的。 You should use shifts (<<) 您应该使用班次(<<)

Some quick and dirty code to do this looks like this; 一些快速而肮脏的代码可以做到这一点。

unsigned int somevalue = 3543577; 
char hexout[9];
const char *hexchar = "0123456789ABCDEF";
for(int i=7; i>=0; i--, somevalue >>= 4) 
    hexout[i] = hexchar[somevalue & 0xF];
hexout[8] = 0;

printf("%s\n",hexout);

Watch out for assumption on sizeof int etc. 注意有关sizeof int等的假设。

You're making it much more difficult than it needs to be. 您正在使它变得比原来困难得多。

  • Avoid using floating point - such as pow() - when working with integral types. 处理整数类型时,请避免使用浮点数(例如pow() It introduces a whole range of artifacts, due to limited precision of floating point. 由于浮点数的精度有限,它引入了整个工件。 Use operations on integral types only. 仅对整数类型使用操作。
  • %s format requires a zero terminated string (array of char ). %s格式需要一个零终止的字符串( char数组)。 Hex[k] is a single character - which is a type mismatch. Hex[k]是单个字符-这是类型不匹配。 printf() gives undefined behaviour if the format specifier and the type of the corresponding argument don't match. 如果格式说明符和相应参数的类型不匹配,则printf()给出未定义的行为。

If you really must do this in a loop, the approach is simple. 如果您确实必须循环执行此操作,则此方法很简单。 Note I'm assuming original_value is positive, and that you don't need to keep its original value. 注意,我假设original_value为正,并且您不需要保留其原始值。

char Hex[9];
const char hex_digits[] = "0123456789ABCDEF";
for (int i = 0; i < 8; ++i)
{
    Hex[7-i] = hex_digits[original_value % 16];
    original_value /= 16;   
}
Hex[8] = '\0';

The assumption that original_value is positive is vital because the modulo operator ( original_value % 16 ) will produce a value between 0 and 15 inclusive, and integer division ( original_value /= 16 ) rounds toward zero. original_value为正的假设至关重要,因为取模运算符( original_value % 16 )将产生一个介于015之间的值(包括015 ,并且整数除法( original_value /= 16 )会四舍五入为零。

This will add leading zeros, so the output string for a value of 300 will be "0000012C". 这将添加前导零,因此值300的输出字符串将为“ 0000012C”。 I'll leave it as an exercise to work out how to get leading spaces rather than leading zeros. 我将把它留作练习,以弄清楚如何获得前导空格而不是前导零。

You can also do the above using equivalent bitwise operations, but I'll leave that as an exercise. 您也可以使用等效的按位运算来完成上述操作,但我将其保留为练习。 I consider using basic math operations is clearer for this exercise (most people, if asked to write some value on paper in hex, would work in terms of division and remainders, not bit fiddling). 我认为使用基本的数学运算可以更轻松地进行此练习(大多数人,如果被要求用十六进制在纸上写一些值,则可以进行除法运算和余数运算,而不是一点点摆弄)。

However, the above (even trying to do it in a loop) is unnecessary. 但是,上述操作(即使尝试循环执行)也是不必要的。 All you really need to do is; 您真正需要做的只是;

 char Hex[9];
 sprintf(Hex, "%08X", (unsigned)original_value);

If you want spaces instead of leading zeros, remove the 0 from the format string. 如果要空格而不是前导零,请从格式字符串中删除0

Note that I have increased the dimension of Hex by 1 . 请注意,我已将Hex的尺寸增加了1 This allows for sprintf() to append a trailing zero (and prevents undefined behaviour, since sprintf() ASSUMES the array provided is large enough to include that trailing character). 这允许sprintf()附加尾随零(并防止未定义的行为,因为sprintf()会提供所提供的数组足够大以包含该尾随字符)。 That will also allow you to print using 这也将使您可以使用

 printf("%s", Hex);

which keeps printing characters until a trailing zero byte is found. 一直打印字符,直到找到结尾的零字节。

If you don't want the trailing zero character in the array, obviously you need to adjust logic above. 如果您不希望数组中的尾随零字符,显然您需要调整上面的逻辑。 But you also need to avoid trying to print the array as a string (eg using the %s format). 但是,您还需要避免尝试将数组打印为字符串(例如,使用%s格式)。

Bear in mind that your question ASSUMES int is a 32-bit type (a larger array would be needed for 64-bit types, for example). 请记住,您的问题ASSUMES int是32位类型(例如,对于64位类型,将需要更大的数组)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM