Easiest way to convert int to string in C++

后端 未结 28 1845
甜味超标
甜味超标 2020-11-21 06:42

What is the easiest way to convert from int to equivalent string in C++. I am aware of two methods. Is there any easier way?

(1)



        
28条回答
  •  猫巷女王i
    2020-11-21 07:37

    EDITED. If you need fast conversion of an integer with a fixed number of digits to char* left-padded with '0', this is the example for little-endian architectures (all x86, x86_64 and others):

    If you are converting a two-digit number:

    int32_t s = 0x3030 | (n/10) | (n%10) << 8;
    

    If you are converting a three-digit number:

    int32_t s = 0x303030 | (n/100) | (n/10%10) << 8 | (n%10) << 16;
    

    If you are converting a four-digit number:

    int64_t s = 0x30303030 | (n/1000) | (n/100%10)<<8 | (n/10%10)<<16 | (n%10)<<24;
    

    And so on up to seven-digit numbers. In this example n is a given integer. After conversion it's string representation can be accessed as (char*)&s:

    std::cout << (char*)&s << std::endl;
    

    NOTE: If you need it on big-endian byte order, though I did not tested it, but here is an example: for three-digit number it is int32_t s = 0x00303030 | (n/100)<< 24 | (n/10%10)<<16 | (n%10)<<8; for four-digit numbers (64 bit arch): int64_t s = 0x0000000030303030 | (n/1000)<<56 | (n/100%10)<<48 | (n/10%10)<<40 | (n%10)<<32; I think it should work.

提交回复
热议问题