converting BYTE to STRING

hello
if it's not the best place to ask,i am new here :)
i want to get any macadreses from current machine and use it as string;

it's reading up to 16 mac code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
 #include "stdafx.h"
#include <Windows.h>
#include <Iphlpapi.h>
#include <Assert.h>
#include <cstdlib> // fucking system pause
#pragma comment(lib, "iphlpapi.lib")


static void GetMACaddress(void)
{
	IP_ADAPTER_INFO AdapterInfo[16];			// Allocate information for up to 16 NICs
	DWORD dwBufLen = sizeof(AdapterInfo);		// Save the memory size of buffer

	DWORD dwStatus = GetAdaptersInfo(			// Call GetAdapterInfo
		AdapterInfo,							// [out] buffer to receive data
		&dwBufLen);								// [in] size of receive data buffer
	assert(dwStatus == ERROR_SUCCESS);			// Verify return value is valid, no buffer overflow

	PIP_ADAPTER_INFO pAdapterInfo = AdapterInfo;// Contains pointer to current adapter info
	do {
		printf("MAC Address: %02X%02X%02X%02X%02X%02X\n", 
		pAdapterInfo->Address[0], pAdapterInfo->Address[1], pAdapterInfo->Address[2],
		pAdapterInfo->Address[3], pAdapterInfo->Address[4], pAdapterInfo->Address[5]);
		
		pAdapterInfo = pAdapterInfo->Next;		// Progress through linked list
	}
	while(pAdapterInfo);						// Terminate if last adapter
}

int _tmain(int argc, _TCHAR* argv[])
{
	GetMACaddress();							// Obtain MAC address of adapters
	system("pause");

	return 0;
}

in first place i tryed to read frst 2byte of mac (pAdapterInfo->Address[0]) passing it to getascii()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
string getascii(char n1)
{
	int n = (int)n1;
	ostringstream num;
	string ss;
	int a[30];
	int i = 0;
	while (n>0)
	{
		a[i] = n % 16;
		n = (int)n / 16;
		i++;
	}
	for (int j = i - 1; j >= 0; j--)
	{
		if (a[j]<10)
		{
			num << a[j];
			ss = num.str();
		}
		if (a[j] >= 10)
		{
			switch (a[j])
			{
			case 10:ss += "A"; break;
			case 11:ss += "B"; break;
			case 12:ss += "C"; break;
			case 13:ss += "D"; break;
			case 14:ss += "E"; break;
			case 15:ss += "F"; break;
			}
		}
	}
	//return printf("%s", ss);
	return ss;
}

and then convert it to string and adding one by one to string so i can use it.
is this whole work good idea?
my goal is that if it's possible make a class or function , call it and it return some string that hold each mac adres of local machin.
is there is any thing like that?
i repate the return macaddres MUST be string so i could use it for another perpose.

another gestion is about HDD Serial
here it's my cods that retrun Serial of drive C :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
#include "stdafx.h"
#define _WIN32_DCOM
#include <iostream>
using namespace std;
#include <comdef.h>
#include <Wbemidl.h>
#include "Comdef.h"

# pragma comment(lib, "wbemuuid.lib")

BSTR mhm_ath()
{
	HRESULT hres;

	// Step 1: --------------------------------------------------
	// Initialize COM. ------------------------------------------

	hres = CoInitializeEx(0, COINIT_MULTITHREADED);
	if (FAILED(hres))
	{
		cout << "Failed to initialize COM library. Error code = 0x"
			<< hex << hres << endl;
		//return 1;                  // Program has failed.
	}

	// Step 2: --------------------------------------------------
	// Set general COM security levels --------------------------

	hres = CoInitializeSecurity(
		NULL,
		-1,                          // COM authentication
		NULL,                        // Authentication services
		NULL,                        // Reserved
		RPC_C_AUTHN_LEVEL_DEFAULT,   // Default authentication 
		RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation  
		NULL,                        // Authentication info
		EOAC_NONE,                   // Additional capabilities 
		NULL                         // Reserved
		);


	if (FAILED(hres))
	{
		cout << "Failed to initialize security. Error code = 0x"
			<< hex << hres << endl;
		CoUninitialize();
		//return 1;                    // Program has failed.
	}

	// Step 3: ---------------------------------------------------
	// Obtain the initial locator to WMI -------------------------

	IWbemLocator *pLoc = NULL;

	hres = CoCreateInstance(
		CLSID_WbemLocator,
		0,
		CLSCTX_INPROC_SERVER,
		IID_IWbemLocator, (LPVOID *)&pLoc);

	if (FAILED(hres))
	{
		cout << "Failed to create IWbemLocator object."
			<< " Err code = 0x"
			<< hex << hres << endl;
		CoUninitialize();
		//return 1;                 // Program has failed.
	}

	// Step 4: -----------------------------------------------------
	// Connect to WMI through the IWbemLocator::ConnectServer method

	IWbemServices *pSvc = NULL;

	// Connect to the root\cimv2 namespace with
	// the current user and obtain pointer pSvc
	// to make IWbemServices calls.
	hres = pLoc->ConnectServer(
		_bstr_t(L"ROOT\\CIMV2"), // Object path of WMI namespace
		NULL,                    // User name. NULL = current user
		NULL,                    // User password. NULL = current
		0,                       // Locale. NULL indicates current
		NULL,                    // Security flags.
		0,                       // Authority (for example, Kerberos)
		0,                       // Context object 
		&pSvc                    // pointer to IWbemServices proxy
		);

	if (FAILED(hres))
	{
		cout << "Could not connect. Error code = 0x"
			<< hex << hres << endl;
		pLoc->Release();
		CoUninitialize();
		//return 1;                // Program has failed.
	}

	cout << "Connected to ROOT\\CIMV2 WMI namespace" << endl;


	// Step 5: --------------------------------------------------
	// Set security levels on the proxy -------------------------

	hres = CoSetProxyBlanket(
		pSvc,                        // Indicates the proxy to set
		RPC_C_AUTHN_WINNT,           // RPC_C_AUTHN_xxx
		RPC_C_AUTHZ_NONE,            // RPC_C_AUTHZ_xxx
		NULL,                        // Server principal name 
		RPC_C_AUTHN_LEVEL_CALL,      // RPC_C_AUTHN_LEVEL_xxx 
		RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
		NULL,                        // client identity
		EOAC_NONE                    // proxy capabilities 
		);

	if (FAILED(hres))
	{
		cout << "Could not set proxy blanket. Error code = 0x"
			<< hex << hres << endl;
		pSvc->Release();
		pLoc->Release();
		CoUninitialize();
		//return 1;               // Program has failed.
	}

	// Step 6: --------------------------------------------------
	// Use the IWbemServices pointer to make requests of WMI ----

	// For example, get the name of the operating system
	IEnumWbemClassObject* pEnumerator = NULL;
	hres = pSvc->ExecQuery(
		bstr_t("WQL"),
		bstr_t("SELECT * FROM Win32_LogicalDisk"),
		WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
		NULL,
		&pEnumerator);
	//
	if (FAILED(hres))
	{
		cout << "Query for operating system name failed."
			<< " Error code = 0x"
			<< hex << hres << endl;
		pSvc->Release();
		pLoc->Release();
		CoUninitialize();
		//return 1;               // Program has failed.
	}

	// Step 7: -------------------------------------------------
	// Get the data from the query in step 6 -------------------

	IWbemClassObject *pclsObj = NULL;
	ULONG uReturn = 0;

	while (pEnumerator)
	{
		HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1,
			&pclsObj, &uReturn);
		//cout << pclsObj;
		if (0 == uReturn)
		{
			break;
		}

		VARIANT vtProp;

		// Get the value of the Name property
		hr = pclsObj->Get(L"VolumeSerialNumber", 0, &vtProp, 0, 0);
		wcout << " hard_serial : " << vtProp.bstrVal << endl;
		VariantClear(&vtProp);

		pclsObj->Release();

		stringstream *a;
		string b;
		//*vtProp.bstrVal >> a;
		BSTR c=vtProp.bstrVal;
		SysFreeString (c);

		return c;
		

		//return vtProp.bstrVal;
	}

	// Cleanup
	// ========

	pSvc->Release();
	pLoc->Release();
	pEnumerator->Release();
	CoUninitialize();

	return 0;   // Program successfully completed.

}

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

	printf("%c", mhm_ath());
	system("pause");

}

same as above , i need it as string not BSTR :(
what's the best way to reach this serial as string :)
is this serial permanent or it changes after installing OS or after changing partition format?

look like i need a finger print of pc but evry element must return as string.
and please suggest me some king of this IDes that are permanent and wont change during system os instalation.
sorry for bad spell.

and last thing advice me a good refrence for :
work on type defenation/convert BYTE to STRING etc.

thank's i advance DBBJA.

Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
#include <windows.h>
#include <vector>

#pragma comment( lib, "oleaut32.lib" ) // SysAllocString

std::string byte_seq_to_string( const unsigned char bytes[], std::size_t n )
{
    std::ostringstream stm ;
    stm << std::hex << std::uppercase ;

    for( std::size_t i = 0 ; i < n ; ++i )
        stm << std::setw(2) << std::setfill( '0' ) << unsigned( bytes[i] ) ;

    return stm.str() ;
}

template < std::size_t N > std::string byte_seq_to_string( const unsigned char( &byte_array )[N] )
{ return byte_seq_to_string( byte_array, N ) ; }

std::string wstring_to_string( std::wstring wstr )
{
    // https://msdn.microsoft.com/en-us/library/windows/desktop/dd374130(v=vs.85).aspx
    const auto sz = ::WideCharToMultiByte( CP_UTF8, 0, wstr.data(), wstr.size(), nullptr, 0, nullptr, nullptr );
    std::vector<char> vec(sz) ;
    ::WideCharToMultiByte( CP_UTF8, 0, wstr.data(), wstr.size(), vec.data(), vec.size(), nullptr, nullptr );
    return { vec.begin(), vec.end() } ;
}

std::string bstr_to_string( const BSTR bstr ) { return wstring_to_string(bstr) ; }

int main()
{
    const unsigned char bytes[] = { 255, 23, 32, 56, 1 } ;
    std::string str = byte_seq_to_string(bytes) ;
    std::cout << str << '\n' ;

    const BSTR bstr = ::SysAllocString( L"Hello world" ) ;
    str = bstr_to_string(bstr) ;
    std::cout << str << '\n' ;
    ::SysFreeString(bstr) ;
}

http://rextester.com/JNN78810
Last edited on
thank you,i assume this is BSTR to string, how about other questions?
anyone else?
> assume this is BSTR to string

Also array of bytes to string.


> is this serial permanent or it changes after installing OS or after changing partition format?

The serial number of the physical disk drive is allocated by the manufacturer of the device. This will not change.

The volume id of a partition may be changed.
https://technet.microsoft.com/en-us/sysinternals/bb897436
thank you for replay.
i have a error here :
 
	return{ vec.begin(), vec.end() };

 
Error	1	error C2059: syntax error : '{'	c:\users\xxxx\documents\visual studio 2010\projects\temporariproject\temporariproject\temporariproject.cpp	32	1	temporariproject

using vs 2010 and even using vs 2013 same error,
so in microsoft visual studio what i missed?
Visual Studio 2013: The code will compile cleanly if Update 4 is applied. http://rextester.com/JNN78810

This change would make it work with all versions:
1
2
// return{ vec.begin(), vec.end() };
return std::string( vec.begin(), vec.end() ) ;

http://rextester.com/XVFW45782

See: http://www.stroustrup.com/C++11FAQ.html#uniform-init
yes indeed,it's work with your guide
thank you again JLBorges
Topic archived. No new replies allowed.