how to convert base10 decimal (big endian) to binary ( a hex in little endian) in a char array [closed]

爷,独闯天下 提交于 2019-12-13 10:52:24

问题


I'm having some trouble in iOS. I have been trying to convert a base10 decimal value into a little endian, hexadecimal string.

So far I am unable to do so.

For example I would like to convert the following integer in little endian hexadecinmal:

int val = 11234567890123456789112345678911;


回答1:


You could do it like this:

#include <stdio.h>
#include <string.h>

void MulBytesBy10(unsigned char* buf, size_t cnt)
{
  unsigned carry = 0;
  while (cnt--)
  {
    carry += 10 * *buf;
    *buf++ = carry & 0xFF;
    carry >>= 8;
  }
}

void AddDigitToBytes(unsigned char* buf, size_t cnt, unsigned char digit)
{
  unsigned carry = digit;
  while (cnt-- && carry)
  {
    carry += *buf;
    *buf++ = carry & 0xFF;
    carry >>= 8;
  }
}

void DecimalIntegerStringToBytes(unsigned char* buf, size_t cnt, const char* str)
{
  memset(buf, 0, cnt);

  while (*str != '\0')
  {
    MulBytesBy10(buf, cnt);
    AddDigitToBytes(buf, cnt, *str++ - '0');
  }
}

void PrintBytesHex(const unsigned char* buf, size_t cnt)
{
  size_t i;
  for (i = 0; i < cnt; i++)
    printf("%02X", buf[cnt - 1 - i]);
}

int main(void)
{
  unsigned char buf[16];

  DecimalIntegerStringToBytes(buf, sizeof buf, "11234567890123456789112345678911");

  PrintBytesHex(buf, sizeof buf); puts("");

  return 0;
}

Output (ideone):

0000008DCCD8BFC66318148CD6ED543F

Converting the resulting bytes into a hex string (if that's what you want) should be trivial.




回答2:


Answer: You can't. This number would require a 128 bits integer.




回答3:


Other problems aside (that have already been pointed out by others so I won't repeat), if you do ever need to swap endianness - say you are doing something cross platform (or working with audio sample formats for another example) where it matters to do so, there are some functions provided by Core Foundation, such as CFSwapInt32HostToBig().

For more information on those functions check out the Byte-Order Utilities Reference pages, and you may find what you are looking for.



来源:https://stackoverflow.com/questions/15556572/how-to-convert-base10-decimal-big-endian-to-binary-a-hex-in-little-endian-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!