Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Convert BitStream to String #89

Open
futurumesta opened this issue May 10, 2024 · 1 comment
Open

Convert BitStream to String #89

futurumesta opened this issue May 10, 2024 · 1 comment

Comments

@futurumesta
Copy link

Hello!

Is it possible to get all the data from BitStream in the form of HEX (as an example 42A1F5A1AA363F ...) as a string?

public OnIncomingRawPacket(playerid, packetid, BitStream:bs)
{
new some_data[2048];
BS_ReadValue() //????
printf("String hex data: %s", some_data);
return 1;
}
@Naseband
Copy link

Naseband commented Aug 7, 2024

It's quite easy to do, you can use PR_BITS to get an arbitrary amount of bits and then format them as hex in a loop.

Note that raknet bitstreams are neither aligned nor padded. Meaning single bits (ie. bool) will cause the rest of the data to no longer be aligned with the half-byte or byte boundaries of the displayed hex (one single digit in hex represents 4 bits of data).
Without knowing the parameter list you cannot meaningfully format it, so keep that in mind.

I made this some time ago, you can use it if you still need it.
The code can be heavily simplified, but I wanted to add some readability in the output (and a simple display if the end if there are for example 3 bits leftover).

static hex_data[2048];
hex_data = "";

new hex_len = 0,
    tmp_text[6],
    total_bits,
    bits_left,
    character_count = 0;

BS_GetNumberOfBitsAllocated(bs, total_bits); // Use BS_GetNumberOfUnreadBits if you want to BS_IgnoreBits before this
bits_left = total_bits;

while(bits_left > 0)
{
    new read_len = bits_left > 4 ? 4 : bits_left,
        value;

    BS_ReadValue(bs, PR_BITS, value, read_len);
    bits_left -= read_len;

    if(read_len == 4)
        format(tmp_text, sizeof(tmp_text), "%x", value);
    else
        format(tmp_text, sizeof(tmp_text), "%x{%i}", value, read_len); // If not a full half-byte, display the number of bits (this only happens on the last chunk)

    if((++character_count) % 2 == 0) // Spacing, optional
        strcat(tmp_text, " ");

    if(hex_len + strlen(tmp_text) >= sizeof(hex_data) - sizeof(tmp_text)) // Cannot append more
    {
        strcat(hex_data, "...");
        break;
    }

    hex_len += strcat(hex_data, tmp_text);
}

BS_ResetReadPointer(bs); // Only required if you want to do something else with this bs handle.

printf("rpc %i [%i]: %s", rpcid, total_bits, hex_data);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants