Veteran Member
Join Date: Jan 2010
Location: Russia, Ivanovo
|
04-29-2017
, 21:24
Re: [ H3LP ] Converter bitsum to string?
|
#11
|
Try this:
PHP Code:
#include <amxmodx>
enum PlayerFlags (<<= 1) { PF_Alive = 1, PF_InWater, PF_OnGround, PF_Bot, PF_Hltv };
// This violates the DRY principle, but idk how to do this without repeating // (I think there is no way to avoid this in Pawn, // because macros and syntax aren't so powerful, // I know how to do this in C++, but there is no way) new const PlayerFlagsStrings[][] = { "PF_Alive", "PF_InWater", "PF_OnGround", "PF_Bot", "PF_Hltv" };
public plugin_init() { server_print("%s", PlayerFlags_Serialize(PF_Hltv)); server_print("%s", PlayerFlags_Serialize(PF_Alive | PF_OnGround)); server_print("%d", PlayerFlags_Deserialize("PF_Hltv")); server_print("%d", PlayerFlags_Deserialize("PF_Alive, PF_OnGround")); }
stock PlayerFlags_Serialize(PlayerFlags:value) { return BitFlagsEnum_Serialize(PlayerFlagsStrings, value); }
stock PlayerFlags:PlayerFlags_Deserialize(const value[]) { static Trie:valuesMap = Invalid_Trie; if (valuesMap == Invalid_Trie) { valuesMap = TrieCreate(); for (new i = 0; i < sizeof(PlayerFlagsStrings); i++) { TrieSetCell(valuesMap, PlayerFlagsStrings[i], (1 << i)); } } return BitFlagsEnum_Deserialize(valuesMap, value); }
const MaxSerializedStringSize = 256; // TODO: error checking? optimizing? stock BitFlagsEnum_Serialize(const valuesMap[][], any:value) { static serialized[MaxSerializedStringSize]; // foreach bit from lower to higher for (new temp = _:value, bitNumber = 0, bool:wasWrittenSomething = false, serializedLength = 0; temp != 0; temp >>= 1, ++bitNumber ) { if (temp & 1 == 0) { continue; } if (wasWrittenSomething) { serializedLength += formatex(serialized[serializedLength], charsmax(serialized) - serializedLength, ", %s", valuesMap[bitNumber] ); } else { serializedLength += copy(serialized, charsmax(serialized), valuesMap[bitNumber]); wasWrittenSomething = true; } } return serialized; }
// TODO: error checking? optimizing? stock any:BitFlagsEnum_Deserialize(Trie:valuesMap, const value[]) { static remainPart[MaxSerializedStringSize]; const MaxSerializedValueStringSize = 64; static currentValue[MaxSerializedValueStringSize]; strtok(value, currentValue, charsmax(currentValue), remainPart, charsmax(remainPart), ',', .trimSpaces = true ); new deserialized; TrieGetCell(valuesMap, currentValue, deserialized); while (remainPart[0] != EOS) { strtok(remainPart, currentValue, charsmax(currentValue), remainPart, charsmax(remainPart), ',', .trimSpaces = true ); new temp; TrieGetCell(valuesMap, currentValue, temp); deserialized |= temp; } return deserialized; }
It would print:
Code:
PF_Hltv
PF_Alive, PF_OnGround
16
5
__________________
|
|