It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,
visit the help center.
Closed 6 years ago.
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;
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.
Answer: You can't. This number would require a 128 bits integer.
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.