C++ 使用ascii值将字符数组中的多个ascii字符转换为单个整数--c/c++;
有人知道一个很好的转换方法吗 例如,以包含ascii字符“ABC”的字符数组为例,我正在寻找的int转换将这些字符更改为值为656667的单个int 任何帮助都将不胜感激 编辑 非常感谢您的回复。正如有人指出的,我确实说过char数组,特别是这是一个字节数组,因此可能有多个“\0”或NULL元素后跟其他ascii。使用strlen等方法会导致问题。再次感谢您当前的输入。C++ 使用ascii值将字符数组中的多个ascii字符转换为单个整数--c/c++;,c++,c,ascii,C++,C,Ascii,有人知道一个很好的转换方法吗 例如,以包含ascii字符“ABC”的字符数组为例,我正在寻找的int转换将这些字符更改为值为656667的单个int 任何帮助都将不胜感激 编辑 非常感谢您的回复。正如有人指出的,我确实说过char数组,特别是这是一个字节数组,因此可能有多个“\0”或NULL元素后跟其他ascii。使用strlen等方法会导致问题。再次感谢您当前的输入。#包括 #include <stdio.h> #include <string.h> int main
#包括
#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);
}
#包括
int main()
{
char*str=“ABC”;
inti,n;
(i=0,n=0;i使用C++,取结果字符串并将其转换为OP作为int的练习。
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() );
}
}
std::字符串StringToDec(const char*inString)
{
if(inString==NULL)
{
返回“”;
}
其他的
{
std::ostringstream缓冲区;
标准::字符串=指令串;
for(std::string::iterator it=string.begin();it!=string.end();it++)
{
C中的缓冲区
#包括
#包括
int main(){
char start[]=“ABC”;
字符输出[100];
int i;
char*output\u start=输出;
对于(i=0;i#包括
#包括
内部主(空)
{
char*input=“ABC”;
字符输出[256];
int n=0;
while(*输入)
n+=sprintf(输出+n,“%d”,*输入++);
printf(“%d\n”,atoi(输出));
返回0;
}
依赖于以null结尾的字符串。根据需要,输出的硬代码大小。我在你的帖子中注意到你说的是“字符数组”--值得注意的是,不是字符串。假设你实际上指的是字符数组而不是以null结尾的字符串,那么所有发布的sprintf类型的解决方案都不起作用
这里有一个不使用字符串处理的简单数学方法
char str [] = {'A','B','C'};
int ret = 0;
for( int i = 0; i < sizeof(str); ++i )
{
ret *= 100;
ret += str[i];
}
charstr[]={'A','B','C'};
int-ret=0;
对于(int i=0;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];
}
int-ret=0;
对于(int i=0;i ret=((大多数小写字母的retASCII值超过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's 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;
}
#包括
#包括
#包括
#包括
内部主(空)
{
静态常量char*const upper=“abcdefghijklmnopqrstuvxyz”;
INTA=65;
/*更改:因为它是一个字符数组,不一定是字符串*/
[3]中的常量字符=“ABC”;
无符号长输出=0;
尺寸i;
对于(i=0;i
(我假设您想要一个值为656667的数字,例如“ABC”
,您不只是想打印。)不完全清楚需要什么样的最终结果。不过,在我看来,转换“ABC”对于整数,656667有很多值。问题是结果不明确。您可能不想将其转换为0x414243吗?如果是,则memcpy可以工作
编辑:如果字符集不限于特定范围(特别是0-99),则结果可能不明确。我认为ASCII字符被认为是从0到127(0x7f)的所有字符。通过将十进制值串联在一起将结果转换为整数,会导致值不明确。例如,字符串“xy”
的单个十进制值为120、121。根据最初的问题定义,结果为120121。这可以被解码为12、01、21或120、121。两者都会产生有效的ASCII字符。但是,在不知道所有问题约束的情况下,这可能是完全有效的。因为它是用于网络协议的,您必须指定endianness。您将字节按一定顺序放入一个int
,并询问值。字节按两个不同的顺序放入int
s。这在一台单独的计算机上并不重要,因为计算机不会一时兴起地更改endianness,但您可以很容易地在两台不同的计算机上获得两个不同的值计算机
也就是说,有多种转换方法。一种是使用联合
,另一种是在int*
(或unsigned int*
)和char*
)之间进行转换。只要确保使用一致的字节顺序即可。大多数情况下,我们必须考虑实际问题
解析数据包协议可能很容易,也可能不容易,这取决于规范,但通常情况下,您可以做得比将其全部放入字符串中更好
如果您不了解它们,请查找googleprotocolbuffer
,它们不能按原样使用,但想法就在那里
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
class-UdpPacket
{
公众:
UdpPacket(const char str[],size\u t length);
uint16_t sourcePort()常量{return mSourcePort;}
unit16_t destinationPort()常量{return mdestinitionport;}
//…其他三位获得者
私人:
uint16_t mSourcePort;
uint16\u t MDESTIONPORT;
uint16最小长度;
uint16_t mCheckSum;
std::字符串mData;
};//类UdpPacket
UdpPacket::UdpPacket(常量字符str[],大小\u t长度):
mSourcePort(0)、mdestationport(0)、mLength(0)、mCheck
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];
}
#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's 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;
}
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
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;
}
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;
}
#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;
}
#include <algorithm>
#include <iostream>
#include <vector>
#include <iterator>
int main()
{
// considering you know the size of buffer here's 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;
}
65 66 0 0 67 100 101 102
#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;
}
stream: 65660067100101102
int value: 0
string value: 65660067100101102