digitalmars.D.learn - char* to long
- Mars (6/7) Jan 24 2012 Hello everybody.
- Mantis (5/12) Jan 24 2012 This seems to work:
- Jonathan M Davis (21/38) Jan 24 2012 Yeah, but note that that's really equivalent to
- mta`chrono (12/12) Jan 24 2012 Why not just go the "good old" way? you char* should be zero terminated
- Mars (2/2) Jan 25 2012 Thanks for the replies, everyone.I guess I'll go with the double
Hello everybody. I have to convert a char* (from a C function) to long. At the moment I'm usinglong foo = to!long( to!string(bar) );but this doesn't feel right... with 2 to calls. Is this the way to go? Or is there something better? Mars
Jan 24 2012
24.01.2012 22:48, Mars пишет:Hello everybody. I have to convert a char* (from a C function) to long. At the moment I'm usingThis seems to work: char[] c = "123\0".dup; auto l = parse!long(c); writeln( l );long foo = to!long( to!string(bar) );but this doesn't feel right... with 2 to calls. Is this the way to go? Or is there something better? Mars
Jan 24 2012
On Tuesday, January 24, 2012 23:02:18 Mantis wrote:24.01.2012 22:48, Mars пишет:Yeah, but note that that's really equivalent to auto foo = to!long(to!(char[])(bar)); except that you're creating an extra variable and using parse with its somewhat different semantics. In either case, you need to convert it from a char* to an actual character array of some kind before converting it to a long, and that means that you're allocating memory. In general, I would recommend just doing what the OP said auto foo = to!long(to!string(bar)); It's the cleanest solution IMHO, and in general, that extra bit of memory allocation isn't a big deal. However, if you know the length of the char*, then you can slice it and pass that to std.conv.to. e.g. auto foo = to!long(bar[0 .. 3]); But you have to know the length of the string already - or use strlen on it to get its length. e.g. auto foo = to!long(bar[0 .. strlen(bar)]); It's quite doable and probably faster than converting to string and then to long, but it's certainly uglier code. This should only be a problem when interfacing with C though, since you really shouldn't be using char*'s or null-terminated strings otherwise. - Jonathan M DavisHello everybody. I have to convert a char* (from a C function) to long. At the moment I'm usingThis seems to work: char[] c = "123\0".dup; auto l = parse!long(c); writeln( l );long foo = to!long( to!string(bar) );but this doesn't feel right... with 2 to calls. Is this the way to go? Or is there something better? Mars
Jan 24 2012
Why not just go the "good old" way? you char* should be zero terminated when coming from c. ==== private import core.stdc.stdlib, std.stdio; void main() { const(char)* str = "1234567890".ptr; long lng = atoll(str); writeln(lng); } ====
Jan 24 2012
Thanks for the replies, everyone.I guess I'll go with the double conversion for now.
Jan 25 2012