cast safe

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • grahamo

    #1

    cast safe

    Doh,

    In my last mail I meant the function atoi instead of sprintf... and I
    also meant to use an int instead of an unsigned int.........

    this is the approach I mean , ignore the other email...sorry :(


    unsigned char* data = foo();
    int result = atoi((char*)dat a)


    Is that correct? Assuming new c++ style casts are used, is the above
    right or completely erroneous.


    Cheers

    Graham


    From: graham_walsh50@ hotmail.com (grahamo)
    Newsgroups: comp.lang.c++
    Subject: cast safe

    NNTP-Posting-Host: 194.206.100.24
    Message-ID: <79528aa8.04121 40618.fe964cc@p osting.google.c om>

    Hi,

    i know I should use the new style casts and I intend to however I
    would like to know how I go about this;

    I have an unsigned char* that a 3rd party API returned to me. The API
    reads text from a file and gives me that test as an unsigned char*.
    For the sake of this example the text string is "100"

    unsigned char* data = foo();

    I need to get this into an unsigned int, which is what it ultimately
    should be however I'm not sure of the best approach. I can cast it to
    a char* and then use sprintf(result, "%d", arg) but I'm not sure if
    thats the best approach.

    What's the *correct* way to achieve it... in terms of code correctness
    and "correct approach".

    Thanks much for any info (as usual:)

    GrahamO
  • Victor Bazarov

    #2
    Re: cast safe

    grahamo wrote:[color=blue]
    > [...]
    > this is the approach I mean , ignore the other email...sorry :(
    >
    >
    > unsigned char* data = foo();
    > int result = atoi((char*)dat a)
    >
    >
    > Is that correct? Assuming new c++ style casts are used, is the above
    > right or completely erroneous.[/color]

    It's commonly used, but it's not the best way, and often is unacceptable.
    'atoi' has no way to report an error. You always get 0 whether it really
    was "0" or it was something that couldn't be converted. Use 'strtol'.
    [color=blue]
    > [...][/color]

    Comment

    Working...