[RESOLVED] convert a int to char array - Page 2
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 2 of 2 FirstFirst 12
Results 16 to 18 of 18

Thread: [RESOLVED] convert a int to char array

  1. #16
    Join Date
    May 2015
    Posts
    111

    Re: convert a int to char array

    Again update to this thread, as it is similar issue:

    I have a string

    string str = "05087000f1";

    I want to know, what is the easiest way this can be converted to following array
    Lets say u8 is typedef to unsigned char.

    Then we need the output in the following format

    u8 ptr[10];

    ptr[0] = 0x05;
    ptr[1] = 0x08;
    ptr[2] = 0x70;
    ptr[3] = 0x00;
    ptr[4] = 0xf1;

  2. #17
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    6,161

    Re: convert a int to char array

    For one way, consider

    Code:
    	const string str = "05087000f1";
    	u8 ptr[5] = {0};
    
    	if ((str.length() % 2) && (str.length() > 10))
    		cout << "Invalid length" << endl;
    	else
    		for (size_t s = 0; s < str.length(); s += 2)
    			ptr[s / 2] = (u8)strtol(str.substr(s, 2).c_str(), NULL, 16);
    
    	for (const auto& p : ptr)
    		cout << "0x" << hex << setw(2) << setfill('0') << (int)p << endl;
    which displays

    Code:
    0x05
    0x08
    0x70
    0x00
    0xf1
    Note that although the code checks for invalid length of str, it doesn't check for invalid non-hex chars within str.
    Last edited by 2kaud; January 24th, 2018 at 10:02 AM.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2017 (15.6.6)

  3. #18
    Join Date
    May 2015
    Posts
    111

    Re: convert a int to char array

    Thanks a lot kaud

Page 2 of 2 FirstFirst 12

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)