Convert multiple ascii characters into a char array into a single int using their ascii values ​​--- c / c ++

Does anyone know a good way to do this conversion?

for example, take a char array containing ascii charcters "ABC", the int transformation I'm looking for will change these characters to a single int with a value of 656667.

Any help would be greatly appreciated.

change really appreciate the answers. as someone noticed that I said a char array, and in particular it is a byte array, so there may be several '\ 0' or NULL elements followed by additional ascii. using methods like strlen etc. will cause problems. thanks again for the current input.

+3
source share
13

.

, , , ...

, Google Protocol Buffer, , .

class UdpPacket
{
public:
  UdpPacket(const char str[], size_t length);

  uint16_t sourcePort() const { return mSourcePort; }
  unit16_t destinationPort() const { return mDestinationPort; }
  // ... The 3 other getters
private:
  uint16_t mSourcePort;
  uint16_t mDestinationPort;
  uint16_t mLength;
  uint16_t mCheckSum;
  std::string mData;
}; // class UdpPacket


UdpPacket::UdpPacket(const char str[], size_t length):
  mSourcePort(0), mDestinationPort(0), mLength(0), mCheckSum(0),
  mData()
{
  if (length < 8) throw IncompleteHeader(str, length);

  memcpy(mSourcePort, str, 2);
  memcpy(mDestinationPort, str, 2);
  memcpy(mLength, str, 2);
  memcpy(mCheckSum, str, 2);
  mData = std::string(str+8, length-8);
} // UdpPacket::UdpPacket

? . , - , memcpy... .

, mData, , , , .

int, , int , , ... int , .

+1

C:

#include <stdio.h>
#include <string.h>

int main(){
    char start[]="ABC";
    char output[100];
    int i;
    char* output_start=output;
    for(i=0;i<3;i++){
        output_start+=sprintf(output_start,"%d",start[i]);
    }
    printf("%s\n",output);
}

sprintf . , , , ASCII char .

. %u %d.

+3

, . , "ABC" 656667 . , . , 0x414243? , memcpy .

: , ( , 0-99). , ASCII 0 127 (0x7f). . , "xy" 120, 121. 120121. 12, 01, 21, 120, 121. ASCII. , , , .

+2

, (* 256) (* 100), .

unsigned int int, / .

, .

unsigned int func(const char s[], size_t size)
{
    const unsigned char *us = (const unsigned char *) s;
    unsigned int result = 0;
    size_t z;
    for (z = 0; z < size; z++)
    {
        result *= 256;
        result += us[z];
    }

    return result;
}

.

+2
#include <stdio.h>
#include <string.h>

int main()
{
  char *str = "ABC";
  int i, n;

  for (i=0,n=0; i<strlen(str); i++, n*=100) {
    n += str[i];
  }
  n /= 100;

  printf("%d\n", n);
}
+1

++, , int OP

std::string StringToDec( const char *inString )
{
    if ( inString == NULL )
    {
        return "";
    }
    else
    {
        std::ostringstream buffer;
        std::string String = inString;

        for ( std::string::iterator it = String.begin(); it != String.end(); it++ )
        {
            buffer << std::setw(2) << std::dec << int(*it);
        }

        return std::string ( buffer.str().c_str() );
    }
}
+1
#include <stdio.h>
#include <stdlib.h>

int main( void )
{
    char * input = "ABC";
    char output[ 256 ];
    int n = 0;

    while( *input )
        n += sprintf( output + n, "%d", *input++ );

    printf( "%d\n", atoi( output ) );

    return 0;
}

. output .

+1

, "char array" - , . , char, , sprintf .

, .

char str [] = {'A','B','C'};
int ret = 0;
for( int i = 0; i < sizeof(str); ++i )
{
    ret *= 100;
    ret += str[i];
}

:

, (, ), :

int ret = 0;
for( int i = 0; i < sizeof(str); ++i )
{
    ret = ((ret << 2) + ret) << 1;  // ret *= 10
    ret = ((ret << 2) + ret) << 1;  // ret *= 10
    ret += str[i];
}

- , 100 - . , 0-256, 3 . , ++ :

char str [] = {0, 123, 'A'};

unsigned __int64 ret = 0;
for( int i = 0; i < sizeof(str); ++i )
{
    ret = ((ret << 2) + ret) << 1;  // ret *= 10
    ret = ((ret << 2) + ret) << 1;  // ret *= 10
    ret = ((ret << 2) + ret) << 1;  // ret *= 10
    ret += str[i];
}
+1

ASCII 99, . , ASCII (.. 'A' - 65, ), . , :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>

int main(void)
{
    static const char *const upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    int A = 65;
    /* changed: since it a char array, not necessarily a string */
    const char in[3] = "ABC";
    unsigned long long out = 0;
    size_t i;

    for (i=0; i < sizeof in; ++i) {
        char *found = strchr(upper, in[i]);
        if (found) {
            if ((ULLONG_MAX - (A + (found - upper))) / 100 < out) {
                fprintf(stderr, "Overflow at %c\n", in[i]);
                return EXIT_FAILURE;
            }
            out = out * 100 + A + (found - upper);
        } else {
            fprintf(stderr, "Giving up at %c\n", in[i]);
            return EXIT_FAILURE;
        }
    }
    printf("%llu\n", out);
    return EXIT_SUCCESS;
}

( , , , , 656667 "ABC", .)

+1

, endianness. int . int . , , .

, . union, - int * ( unsigned int *) char *. , .

+1

, . "AB\0C" 6566067. , 656667, if (!val) rv *= 10;

int asciiToInt(char *str, int len) {
    int i;
    int rv = 0;

    for (i = 0; i < len; i++) {
        int val = str[i];
        if (!val)
            rv *= 10;
        while (val) {
            rv *= 10;
            val /= 10;
        }
        rv += str[i];
    }
    return rv;
}
+1
source

How about this:

#include <iostream>
#include <sstream>
#include <algorithm>

struct printer {
    std::stringstream& s;
    printer(std::stringstream& stream_) : s(stream_) { };
    void operator()(char& c) { s << static_cast<int>(c); } 
};

int main (int argc, char* argv[]) {

    std::stringstream helper;
    char* in = "ABC";
    std::for_each(in, in+3, printer(helper));
    int result;
    helper >> result;
    std::cout << result; // print 656667
    return 0;
}

edit: You requested a conversion to int. I slightly modified the code to do this.

+1
source

Would something like this be “right” for you?

#include <algorithm>
#include <iostream>
#include <vector>
#include <iterator>

int main()
{
        // considering you know the size of buffer here the buffer
        const unsigned char buf[] = {'A', 'B', '\0', '\0', 'C', 'd', 'e', 'f'};
        // 'conversion' happens here
        const std::vector<int> data(buf, buf + sizeof buf/sizeof 0[buf]);

        std::copy(data.begin(), data.end(),
                  std::ostream_iterator<int>(std::cout, " "));

        return 0;
}

Result:

65 66 0 0 67 100 101 102 

Of course, it doesn’t matter that this vector is bound to stringstream, and then from to to int, but it will overflow very quickly:

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

struct PutElementToStream
{
        PutElementToStream(std::stringstream &stream)
                : stream_(stream)
        {}
        void operator()(int value)
        {
                stream_ << value;
        }

private:
        std::stringstream &stream_;
};

int main()
{
        const unsigned char buf[] = {'A', 'B', '\0', '\0', 'C', 'd', 'e', 'f'};
        const std::vector<int> data(buf, buf + sizeof buf/sizeof 0[buf]);

        std::stringstream stream;
        std::for_each(data.begin(), data.end(), PutElementToStream(stream));

        std::cout << "stream: " << stream.str() << "\n";

        int value = 0;
        stream >> value;  // the sample array would overflow an int
        std::cout << "int value: " << value << "\n";

        const std::string string_value(stream.str());
        std::cout << "string value: " << string_value << "\n";

        return 0;
}

Result:

stream: 65660067100101102
int value: 0
string value: 65660067100101102
0
source

Source: https://habr.com/ru/post/1731431/


All Articles