In the C language, how do I convert unsigned long value to a string (char *) and keep my source code portable or just recompile it to work on other platform (without rewriting code?
For example, if I have sprintf(buffer, format, value)
, how do I determine the size of buffer with platform-independent manner?
There are three main ways to convert a long value to a String in Java e.g. by using Long. toString(long value) method, by using String. valueOf(long), and by concatenating with an empty String. You can use any of these methods to convert a long data type into a String object.
An unsigned version of the long long data type. An unsigned long long occupies 8 bytes of memory; it stores an integer from 0 to 2^64-1, which is approximately 1.8×10^19 (18 quintillion, or 18 billion billion). A synonym for the unsigned long long type is uint64 .
Unsigned long variables are extended size variables for number storage, and store 32 bits (4 bytes). Unlike standard longs unsigned longs won't store negative numbers, making their range from 0 to 4,294,967,295 (2^32 - 1).
In fact, it can be implemented as a layer on top of standard C with runtime support for the creation and destruction of objects. What that generally means is that most things you can do in C, you can also do in Objective-C. Casting an unsigned long to a float is done (in both languages) as follows.
const int n = snprintf(NULL, 0, "%lu", ulong_value); assert(n > 0); char buf[n+1]; int c = snprintf(buf, n+1, "%lu", ulong_value); assert(buf[n] == '\0'); assert(c == n);
The standard approach is to use sprintf(buffer, "%lu", value);
to write a string rep of value
to buffer
. However, overflow is a potential problem, as sprintf
will happily (and unknowingly) write over the end of your buffer.
This is actually a big weakness of sprintf, partially fixed in C++ by using streams rather than buffers. The usual "answer" is to allocate a very generous buffer unlikely to overflow, let sprintf output to that, and then use strlen to determine the actual string length produced, calloc a buffer of (that size + 1) and copy the string to that.
This site discusses this and related problems at some length.
Some libraries offer snprintf
as an alternative which lets you specify a maximum buffer size.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With