MCPcopy Create free account
hub / github.com/TASEmulators/fceux / StringToBytes

Function StringToBytes

src/utils/xstring.cpp:280–347  ·  view source on GitHub ↗

parses a string in the same format as BytesToString returns true if success.

Source from the content-addressed store, hash-verified

278///parses a string in the same format as BytesToString
279///returns true if success.
280bool StringToBytes(const std::string& str, void* data, int len)
281{
282 if(str.substr(0,7) == "base64:")
283 {
284 // base64
285 unsigned char* tgt = (unsigned char*)data;
286 for(size_t pos = 7; pos < str.size() && len > 0; )
287 {
288 unsigned char input[4], converted[4];
289 for(int i=0; i<4; ++i)
290 {
291 if(pos >= str.size() && i > 0) return false; // invalid data
292 input[i] = str[pos++];
293 if(input[i] & 0x80) return false; // illegal character
294 converted[i] = Base64Table[input[i]^0x80];
295 if(converted[i] & 0x80) return false; // illegal character
296 }
297 unsigned char outpacket[3] =
298 {
299 static_cast<unsigned char>((converted[0] << 2) | (converted[1] >> 4)),
300 static_cast<unsigned char>((converted[1] << 4) | (converted[2] >> 2)),
301 static_cast<unsigned char>((converted[2] << 6) | (converted[3]))
302 };
303 int outlen = (input[2] == '=') ? 1 : (input[3] == '=' ? 2 : 3);
304 if(outlen > len) outlen = len;
305 memcpy(tgt, outpacket, outlen);
306 tgt += outlen;
307 len -= outlen;
308 }
309 return true;
310 }
311 if(str.size()>2 && str[0] == '0' && toupper(str[1]) == 'X')
312 {
313 // hex
314 int amt = len;
315 int bytesAvailable = str.size()/2;
316 if(bytesAvailable < amt)
317 amt = bytesAvailable;
318 const char* cstr = str.c_str()+2;
319 for(int i=0;i<amt;i++) {
320 char a = toupper(cstr[i*2]);
321 char b = toupper(cstr[i*2+1]);
322 if(a>='A') a=a-'A'+10;
323 else a-='0';
324 if(b>='A') b=b-'A'+10;
325 else b-='0';
326 unsigned char val = ((unsigned char)a<<4)|(unsigned char)b;
327 ((unsigned char*)data)[i] = val;
328 }
329 return true;
330 }
331
332 if(len==1) {
333 int x = atoi(str.c_str());
334 *(unsigned char*)data = x;
335 return true;
336 } else if(len==2) {
337 int x = atoi(str.c_str());

Callers 2

installValueMethod · 0.85
cfg_NewToOldFunction · 0.85

Calls 1

sizeMethod · 0.45

Tested by

no test coverage detected