como hacer byte index a pila index

Como ejemplo:
en este byte hay tres bits en alto
con los indices 2,5,7 respectivamente

Byte:

+-+-+-+-+-+-+-+-+
|0|0|1|0|0|1|0|1|
+-+-+-+-+-+-+-+-+
 0 1 2 3 4 5 6 7

la pila queda así

Pila:

+-+
|2| 0
+-+
|5| 1
+-+
|7| 2
+-+

la función pide tener como argumento el indice del bit en el Byte y retornar el indice que tiene en la pila

f(2)->0 
f(5)->1 
f(7)->2

yo estaba pensando en algo con bitwise pero es mas difícil de lo que creí

Can larger transactions have a lesser fee per byte than smaller ones and still get equally treated?

Is the term “volume discounting” applicable in bitcoin transactions, meaning can a user pay less satoshi/Byte if a few transactions are bundled into one?

In other words, would a fee for a single bundled transaction be less than the sum of fees for several small-sized (in bytes) transactions?

Is the transaction size relevant if fee per byte is the same?

Is the size of the transaction some factor when the miner chooses one transaction over the other, provided that they both have the same fee per byte?

In other words, will the miner prefer larger or smaller transactions if they all have the same fee per byte?

java – Convertir Base64 a array de byte en android

Estoy tratando de convertir una imagen que me torna el servidor que viene en codificada en base64, para eso uso este codigo:

    byte () decodedString = Base64.decode(stringImg.getBytes(), Base64.DEFAULT);
    Bitmap result = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
    ByteArrayOutputStream aOutputStream = new ByteArrayOutputStream();
    result.compress( Bitmap.CompressFormat.PNG, 100, aOutputStream );
    return aOutputStream.toByteArray();

Aveces funciona y otras no, cuando no funciona genera un NullPointerException en esta linea result.compress( Bitmap.CompressFormat.PNG, 100, aOutputStream ) No se por que esta pasando, si alguien sabe el porque o de otra forma de como hacerlo, se lo agradecería

c# – decode `IEnumerable` to string made of 1 byte characters (eg., ASCII)

I’m looking for a more elegant or more efficient way to transcode a IEnumerable<uint> (~ array of 32bits int), which is a compact way to represent a byte(4) array, into a string as array of 8bits char:

public static string UintArraytoString(this IEnumerable<uint> x) =>
    string.Concat(x.Select(o =>
        new string(BitConverter.GetBytes(o).Select(Convert.ToChar).ToArray())));

I’m using .net 5.0. I’m open to use unsafe methods too. I think that one may do something like a reinterpretcast, but the IEnumerable is not necessarily contiguous.

How does Electrum compute seed byte just before BIP-32?

As a newbie in Bitcoin and programming it, I am trying to generate BTC addresses from mnemonic. So I read about the BIPs, and found codes in Github that implement those.

I found out that Electrum doesn’t implement BIP-39 (by default if I have not mistaken), because mnemonics that are invalid in BIP-39 are accepted by Electrum!

So my question is: How does Electrum do its own “From mnemonic to seed” section (atleast for standard wallet)? This “seed byte” is the one to be used in BIP-32 for generating keys, if I have not mistaken.

I tried the following Python psuedocode (from “Electrum Seed Version System”):

hmac = hmac.digest(b"Seed version", b"...(12 word mnemonic)...", hashlib.sha512)
bip32_thing = Bip32(secret = hmac(:32), chain = hmac(32:)) # default: Bip32 main net version (idk what this means)

But my generated master public key and Electrum’s doesn’t match (most likely I misunderstood the “Seed Version System” altogether). Thanks for responding!

In case it helps: I am using bip-utils in Python.

deletion – Storage media byte state from shelf and after different formatting algorithms

We are told to erase (overwrite) sensitive files, not only simply “delete” it (i.e. only remove the information where it exists). For the moment being, I’d like to focus on the following and ignore other aspects (e.g. wear leveling on SSD) that may result in data leaks .

Taking this a step farther: does secure erase / overwriting with a special pattern leave the indication that there was a file? I learned that (full) formatting may behave differently depending on the OS (e.g. write zeros in/since(?) MS Vista (1st comment on this Q). In this example (all zeros), random overwriting even with a close-to-paranoid multipass algorithm such as DOD 5220-2M (last pass writes random data) would indicate that and where was/were some file(s) in the first place on media that has disputedly been used or not – one would needto choose one that produces the original “shelf” pattern.

Questions:

  • How would brand new media from shelf (HDD, SSD, USB drive, SD card…) look like (before a customer posibly (re-)formats it), i.e. all 0, all 1, random 0/1, specific pattern…? (I do not know (but may learn) how to examine non-file data, and I am not sure how “representative this would be)
  • Is there a (at least partial) list of formatting behaviour of the plenty of different OS and OS versions (e.g. Win-8, Win-10, Ubuntu and other distros, Mac-OS, Apple/Andoroid phones…)?

c# – Byte array comparison – efficiency check

I have a TCP Listener with NetworkStream that reads 530 bytes from the Client once a second.
Within the TCP Listener BackgroundWorker, I write those bytes into a MemoryStream, and invoke a method that breaks down the MemoryStream into smaller arrays.
Then, I have another BackgroundWorker that constantly compares those smaller arrays to a set of predefined byte arrays- based on the outcome it performs different tasks

While this works fine for what I’m doing, I wonder if there’s a better, more efficient way of doing it.
Right now, I can see that if I was to increase the frequency of the TCP messages being sent, the second BackgrounndWorker doesn’t keep up…

Here’s my code:

{
    public partial class Form1 : Form
    {
        public TcpListener server = null;
        public TcpClient client;
        public Int32 port = 6100;
        public IPAddress localAddr = IPAddress.Parse("127.0.0.1");
        public MemoryStream memStream = new MemoryStream(2000);
        Byte() bytesFromTCP = new Byte(530);
        byte() SendtoPlcZeroCalPASS = { 0x0A, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x32, 0x2B };
        byte() SendtoPlcZeroCalFAIL = { 0x0A, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x58 };
        byte() SendtoPlcSmokeCalPASS = { 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x03, 0x4C };
        byte() SendtoPlcSmokeCalFAIL = { 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x46, 0xC9 };
        public byte() arrInt1 = new byte(2);
        public byte() _arrInt1 = { 0x10, 0x02 };
        public byte() arrBool1 = new byte(2);
        public byte() _arrBool1 = { 0x01, 0x00 };
        public byte() arrBool2 = new byte(2);
        public byte() _arrBool2 = { 0x01, 0x00 };
        public byte() arrBool3 = new byte(2);
        public byte() _arrBool3 = { 0x01, 0x00 };
        public byte() arrBool4 = new byte(2);
        public byte() _arrBool4 = { 0x01, 0x00 };
        public byte() arrString1 = new byte(256);
        public byte() _arrString1 = new byte(256);
        public byte() arrString2 = new byte(256);
        public byte() arrBool5 = new byte(2);
        public byte() _arrBool5 = { 0x01, 0x00 };
        public byte() arrBool6 = new byte(2);
        public byte() _arrBool6 = { 0x01, 0x00 };
        public byte() arrBool7 = new byte(2);
        public byte() _arrBool7 = { 0x01, 0x00 };
        public byte() arrCrc = new byte(2);
        public Form1()
        {
            InitializeComponent();

            bgWorkerSocketListener.DoWork += bgWorkerSocketListener_DoWork;
            bgWorkerSocketListener.WorkerSupportsCancellation = true; //Allow for the background worker process to be cancelled
            bgWorkerSocketListener.WorkerReportsProgress = true;
            bgWorkerSocketListener.RunWorkerAsync();

            bgWorkerTcpProcessor.DoWork += bgWorkerTcpProcessor_DoWork;
            bgWorkerTcpProcessor.WorkerSupportsCancellation = true; //Allow for the background worker process to be cancelled
            bgWorkerTcpProcessor.WorkerReportsProgress = true;
            bgWorkerTcpProcessor.RunWorkerAsync();
        }
        public void bgWorkerSocketListener_DoWork(object sender, DoWorkEventArgs e) //Start the TCP Listener
        {
            try
            {
                AppendTBoxTcpBytes("Waiting for a connection... " + Environment.NewLine);
                //Create a listener
                server = new TcpListener(localAddr, port);
                //Start listening for client requests.
                server.Start();

                String data = null;

                //Enter the listening loop.
                while (true)
                {
                    //Perform a blocking call to accept requests.
                    client = server.AcceptTcpClient();
                    AppendTBoxTcpBytes("Connected!" + Environment.NewLine);

                    data = null;

                    //Get a stream object for reading and writing
                    NetworkStream stream = client.GetStream();

                    int i;
                    while (client.Connected == true)
                    {
                        try
                        {
                            //Loop to receive all the data sent by the client.
                            while ((i = stream.Read(bytesFromTCP, 0, bytesFromTCP.Length)) != 0)
                            {
                                //Translate data
                                data = BitConverter.ToString(bytesFromTCP);

                                AppendTBoxTcpBytes(" Data: " + Environment.NewLine + data + Environment.NewLine + "Length: " + data.Length
                                                         + Environment.NewLine + DateTime.Now.ToString("dd MMMM yyyy HH:mm:ss"));

                                memStream.Write(bytesFromTCP, 0, bytesFromTCP.Length);
                                this.Invoke(new EventHandler(processMessageMemStr)); //Process incoming message
                                memStream.Position = 0;
                            }
                        }
                        catch (Exception ex){}
                    }
                }
            }
            catch (SocketException ex)
            {
                MessageBox.Show("SocketException: " + ex);
            }
        }
        private void processMessageMemStr(object sender, EventArgs e) //Process received messages from Memory Stream 
        {
            System.Threading.Tasks.Task.Run //Begin a new thread
            (() =>
            {
                try
                {
                    memStream.Position = 0;
                    memStream.Read(arrInt1, 0, 2);
                    memStream.Read(arrBool1, 0, 2);
                    memStream.Read(arrBool2, 0, 2);
                    memStream.Read(arrBool3, 0, 2);
                    memStream.Read(arrBool4, 0, 2);
                    memStream.Read(arrString1, 0, 256);
                    memStream.Read(arrString2, 0, 256);
                    memStream.Read(arrBool5, 0, 2);
                    memStream.Read(arrBool6, 0, 2);
                    memStream.Read(arrBool7, 0, 2);
                    memStream.Read(arrCrc, 0, 2);
                }
                catch (Exception err)
                { MessageBox.Show(err.ToString()); }
            });//thread
        }
        public void bgWorkerTcpProcessor_DoWork(object sender, DoWorkEventArgs e) //Start the TCP Listener
        {
            //System.Threading.Tasks.Task.Run //Begin a new thread
            //(() =>
            //{
                ASCIIEncoding ascii = new ASCIIEncoding();

                while (true)
                {
                    try
                    {
                        if (string.Join(",", arrBool1) == string.Join(",", _arrBool1))
                            pictureBox2.Image = Resources.green_on;
                        else
                            pictureBox2.Image = Resources.led_off;
                        if (string.Join(",", arrBool2) == string.Join(",", _arrBool2))
                            pictureBox1.Image = Resources.green_on;
                        else
                            pictureBox1.Image = Resources.led_off;
                        if (string.Join(",", arrBool3) == string.Join(",", _arrBool3))
                            pictureBox3.Image = Resources.red_on;
                        else
                            pictureBox3.Image = Resources.led_off;
                        if (string.Join(",", arrBool4) == string.Join(",", _arrBool4))
                            pictureBox4.Image = Resources.red_on;
                        else
                            pictureBox4.Image = Resources.led_off;
                        if (string.Join(",", arrBool5) == string.Join(",", _arrBool5))
                            pictureBox5.Image = Resources.green_on;
                        else
                            pictureBox5.Image = Resources.red_on;
                        if (string.Join(",", arrBool6) == string.Join(",", _arrBool6))
                            pictureBox6.Image = Resources.green_on;
                        else
                            pictureBox6.Image = Resources.led_off;
                        if (string.Join(",", arrBool7) == string.Join(",", _arrBool7))
                        {
                            pictureBox7.Image = Resources.green_on;
                            pictureBox8.Image = Resources.led_off;
                        }
                        else
                        {
                            pictureBox7.Image = Resources.led_off;
                            pictureBox8.Image = Resources.green_on;
                        }
                        AppendTBoxAlarm(ascii.GetString(arrString1, 0, 256));
                        AppendTBoxStep(ascii.GetString(arrString2, 0, 256));
                    }
                    catch { }
                }
            //});//thread
        }
        
        private void btnSendToClient_Click_1(object sender, EventArgs e)
        {
            try
            {
                server = new TcpListener(localAddr, port);
                NetworkStream stream = client.GetStream();
                if (cBoxSendToPLC.SelectedItem == "Test1 PASS")
                    stream.Write(SendtoPlcZeroCalPASS, 0, SendtoPlcZeroCalPASS.Length);
                if (cBoxSendToPLC.SelectedItem == "Test2 PASS")
                    stream.Write(SendtoPlcSmokeCalPASS, 0, SendtoPlcZeroCalPASS.Length);
                if (cBoxSendToPLC.SelectedItem == "Test1 FAIL")
                    stream.Write(SendtoPlcZeroCalFAIL, 0, SendtoPlcZeroCalPASS.Length);
                if (cBoxSendToPLC.SelectedItem == "Test2 FAIL")
                    stream.Write(SendtoPlcSmokeCalFAIL, 0, SendtoPlcZeroCalPASS.Length);
                else{}
            }
            catch (Exception err)
            {
                MessageBox.Show("No client is yet connected to the server.n" + "Exception: " + err.Message, "Client not connected", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public void AppendTBoxTcpBytes(string value) //Appends text, prevents UI from freezing
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(AppendTBoxTcpBytes), new object() { value });
                return;
            }
            tBoxTcpBytes.Clear();
            tBoxTcpBytes.Text += value;
        }
        public void AppendTBoxAlarm(string value) //Appends text, prevents UI from freezing
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(AppendTBoxAlarm), new object() { value });
                return;
            }
            tBoxAlarm.Clear();
            tBoxAlarm.Text += value;
        }
        public void AppendTBoxStep(string value) //Appends text, prevents UI from freezing
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(AppendTBoxStep), new object() { value });
                return;
            }
            tBoxStep.Clear();
            tBoxStep.Text += value;
        }
    }
}```

csrf – Why is the .NET 5.0 antiforgery byte array length in bits not a common multiple of 6 and 8?

I was learning how antiforgery tokens work behind the scenes and wrote this article on the possible values a token can have.

When the byte array is converted to base64, there are four left over bits which have two zeros appended to get a group of 6 bits, which can then be converted to a base64 character.

The problem is that this limits the range of values for the last character.

Because the last two bits are always zeros, the last char can only have 16 possible values (A, E, I, M, Q, U, Y, c, g, k, o, s, w, 0, 4, 8) instead of 64.

Wouldn’t this essentially make it easier for hackers to brute force?

Why wouldn’t the designers have made the byte length one less than what it is? Ie. 114 instead of 115? 114*8 = 912 bits which is a common multiple of 6 and 8, which would mean no left over bits that need to be padded with zeros, and would mean the final char could be one of 64 values instead of one of 16. Thus increasing the security.

I’ve done the maths at the end of that article if you’re interested.

c – Does it break strict aliasing rules if I point to byte arrays with packed struct pointers?

I’ve been familiarizing myself with C’s strict aliasing rules. I’ve looked at several examples of what not to do, and it always involves casting floats as ints, or casting structs to uint32_t pointers, which to me is obviously bad.

However, in my embedded code, I frequently need to work with CAN data buffers. These are 8 byte buffers, and in many cases the protocols and interfaces I’m working with pack fields together in their packets without any padding. So in order to keep the code easy to read and work with, I define the packet as a packed struct, and then typecast the CAN frame’s data buffer (a uint8_t(8)) to a struct pointer, and then modify the buffer by modifying the struct.

For example:

#define DATA_SIZE 8
struct can_frame{
    uint32_t canid;
    uint8_t dlc;
    uint8_t data(DATA_SIZE);
}

struct packet_example __attribute__((__packed__)) {
    uint8_t field1;
    uint32_t field2;
    uint16_t field3;
    uint8_t field4;
}
_Static_assert(sizeof(struct packet_example) == DATA_SIZE);

void prepare_packet()
{
    struct can_frame frame;
    struct packet_example * p = (struct packet_example *) &(frame.data(0));
    frame->field1 = 1;
    frame->field2 = 2;
    frame->field3 = 3;
    frame->field4 = 4;
}

Is this considered a valid use of C? Or should I stop doing this? Do I need to enable -fno-strict-aliasing? What are the implications of coding this way?

Compiling this kind of code with -Wall and -Werror doesnt give me any warnings and it proceeds fine. However, after reading about strict aliasing, I’m starting to worry that perhaps I’m doing something wrong that the compiler isn’t warning me about.