Thread overview
char* to long
Jan 24, 2012
Mars
Jan 24, 2012
Mantis
Jan 24, 2012
Jonathan M Davis
Jan 24, 2012
mta`chrono
Jan 25, 2012
Mars
January 24, 2012
Hello everybody.
I have to convert a char* (from a C function) to long. At the moment I'm using
>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
January 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 using
>> 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
>
This seems to work:

char[] c = "123\0".dup;
auto l = parse!long(c);
writeln( l );

January 24, 2012
On Tuesday, January 24, 2012 23:02:18 Mantis wrote:
> 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 using
> > 
> >> 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
> 
> This seems to work:
> 
> char[] c = "123\0".dup;
> auto l = parse!long(c);
> writeln( l );

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 Davis
January 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);
}
====

January 25, 2012
Thanks for the replies, everyone.I guess I'll go with the double conversion for now.