PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label base. Show all posts
Showing posts with label base. Show all posts

Thursday, August 11, 2022

[FIXED] How to convert a binary fraction number into decimal fraction number in R?

 August 11, 2022     base, decimal, fractions, r     No comments   

Issue

I need to write a function that converts a binary fraction number into decimal fraction number in R. e.g. f(0.001) # 0.125

What I did: I searched for the related functions in R packages:

DescTools::BinToDec(0.001) # NA
DescTools::BinToDec("0.001") # NA
base::strtoi(0.001, base=2) # NA
base::strtoi("0.001", base=2) # NA

base::packBits(intToBits(0.001), "integer") # 0
base::packBits(intToBits("0.001"), "integer") # 0

compositions::unbinary(0.001) # 0.001
compositions::unbinary("0.001") # NA

I searched in SOF, found the following:

base2decimal <- function(base_number, base = 2) {
  split_base <- strsplit(as.character(base_number), split = "")
  return(sapply(split_base, function(x) sum(as.numeric(x) * base^(rev(seq_along(x) - 1)))))}
base2decimal(0.001) # NA
base2decimal("0.001") # NA

0.001 is:

(0 * 2^(-1)) + (0 * 2^(-2)) + (1 * 2^(-3)) # 0.125
(0 * 1/2) + (0 * (1/2)^2) + (1 * (1/2)^3) # 0.125
(0 * 0.5) + (0 * (0.5)^2) + (1 * 0.5^3) # 0.125

So, something like sum of the inner product (0,0,1) * (0.5^1, 0.5^2, 0.5^3) seems to finish the problem, I could not figure out how to do this in general case.

javascript case:
How to convert a binary fraction number into decimal fraction number? How to convert binary fraction to decimal lisp case:
Convert fractions from decimal to binary


Solution

You can extend the solution you posted in your question to also include the negative powers of two starting at the position of the decimal separator as follows:

base2decimal <- function(base_number, base = 2) {
    base_number = paste(as.character(base_number), ".", sep = "")
    return (mapply(function (val, sep) {
                      val = val[-sep];
                      if (val[[1]] == "-") {
                          sign = -1
                          powmax = sep[[1]] - 3
                          val = val[-1]
                      } else {
                          sign = 1
                          powmax = sep[[1]] - 2
                      };
                      sign * sum(as.numeric(val) * (base ^ seq(powmax, by = -1, length = length(val))))},
        strsplit(base_number, NULL), gregexpr("\\.", base_number)))
}

This code also works for other bases less than (or equal) 10:

base2decimal(c('0.101', '.101', 0.101, 1101.001, 1101, '-0.101', '-.101', -0.101, -1101.001, -1101))
#[1]   0.625   0.625   0.625  13.125  13.000  -0.625  -0.625  -0.625 -13.125
#[10] -13.000
base2decimal(1110.111)
# 14.875
base2decimal(256.3, 8)
# [1] 174.375


Answered By - martin_joerg
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, August 10, 2022

[FIXED] What do 48 and 87 values refer to when converting hexadecimal to decimal number in C?

 August 10, 2022     base, c, decimal, hex, numbers     No comments   

Issue

I am trying to understand the process of converting a hexadecimal number to its decimal equivalent, in particular when converting each hexadecimal digit to its decimal value.

Say when the digit i of hexVal equals any characters ranging from '0' to '9', its decVal equals the hexVal subtracted by 48 and then timed by the digitBase:

if ((hexVal[i] >= '0') && (hexVal[i] <= '9')) {
    decVal += (hexVal[i] - 48) * digitBase;
    ...
}

I understand that 48 is ASCII value of '0'. What I am in doubt with is where the values 55 and 87 come from when digit i of hexVal equals the ranges 'A' to 'F' and 'a' to 'f':

else if ((hexVal[i] >= 'A') && (hexVal[i] <= 'F')) {
    hexToDec += (hexVal[i] - 55) * digitBase;
    ...
}

and

else if ((hexVal[i] >= 'a') && (hexVal[i] <= 'f')) {
    hexToDec += (hexVal[i] - 87) * digitBase;
    ...
}

The code blocks above are extracted from the following function which works well to convert hexadecimal numbers to their equivalent decimals.

int conv_hex_to_dec(char hexVal[]) {

    int hexToDec = 0;
    int len = strlen(hexVal);
    int digitBase = 1; 

    // Extract hex characters as digits from last character
    for (int i = len - 1; i >= 0; i--) {

        if ((hexVal[i] >= '0') && (hexVal[i] <= '9')) {
            hexToDec += (hexVal[i] - 48) * digitBase;
            digitBase = digitBase * 16;
        }

        else if ((hexVal[i] >= 'A') && (hexVal[i] <= 'F')) {
            hexToDec += (hexVal[i] - 55) * digitBase; 
            digitBase = digitBase * 16;
        }
        else if ((hexVal[i] >= 'a') && (hexVal[i] <= 'f')) {
            hexToDec += (hexVal[i] - 87) * digitBase; 
            digitBase = digitBase * 16;
        }
        else {
            printf("Invalid hex val");
        }
    }

    return hexToDec;
}

Any explanation will be much appreciated.

Thanks.


Solution

48 is the ASCII code for '0'; the ASCII codes for 'A' and 'a' are 65 (55 = 65-10) and 97 (87 = 97 - 10) respectively.



Answered By - Scott Hunter
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, July 20, 2022

[FIXED] How to convert a binary to a base10 (decimal) integer in elixir

 July 20, 2022     base, elixir, encoding, erlang, int     No comments   

Issue

I would like to be able to convert an elixir string(binary) to a base10 integer.

I have been able to do this with the following...

<<104, 101, 108, 108, 111>> # equal to string "hello"
|> Base.encode16()
|> Integer.parse(16)

{448378203247, ""}

The above does what I am after but, feels a little like a hack. I would like to...

  • better understand what exactly is happening here
  • know if/how I would be able to do this in one step

Solution

Since Elixir strings are just binaries, you could probably use the erlang :binary.decode_unsigned function to convert binary digits to integers

From the documentation http://erlang.org/doc/man/binary.html#decode_unsigned-1

iex> :binary.decode_unsigned("hello")
448378203247

iex> :binary.encode_unsigned(448378203247)
"hello"

Essentially, the ascii values of hello is

<<104, 101, 108, 108, 111>>

when converted from decimal to hex can be written as

<<68, 65, 6C, 6C, 6F>>

or in binary as

<01101000, 01100101, 01101100, 01101100, 01101111>

which is a series of bytes stored as

68656C6C6F in hex or

01101000_01100101_01101100_01101100_01101111 in binary

whose decimal(base-10) value would be 448378203247

iex> Integer.to_string(448378203247, 16)
"68656C6C6F"

iex> Integer.to_string(448378203247, 2)
"110100001100101011011000110110001101111"
# each byte separated by _ is
# "1101000_01100101_01101100_01101100_01101111"
# missing a leading zero at the left, which doesn't change the value

edit: added binary example,

also, two hex digits can be used to perfectly denote a byte(4 bits needed to encode 16 values, 0 to 15) which is why when we denote in hex, we can just concatenate the hex values and not when they are in decimal(base-10) notation

From The wiki for hexadecimal

Hexadecimal numerals are widely used by computer system designers and programmers, as they provide a more human-friendly representation of binary-coded values. Each hexadecimal digit represents four binary digits, also known as a nibble, which is half a byte. For example, a single byte can have values ranging from 0000 0000 to 1111 1111 in binary form, which can be more conveniently represented as 00 to FF in hexadecimal.



Answered By - S.B
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, July 9, 2022

[FIXED] What really is the purpose of "base" keyword in c#?

 July 09, 2022     base, c#, keyword     No comments   

Issue

Thus for used base class for some commom reusable methods in every page of my application...

public class BaseClass:System.Web.UI.Page
{
   public string GetRandomPasswordUsingGUID(int length)
   {
      string guidResult = System.Guid.NewGuid().ToString();
      guidResult = guidResult.Replace("-", string.Empty);
      return guidResult.Substring(0, length);
   }
}

So if i want to use this method i would just do,

public partial class forms_age_group : BaseClass
{
      protected void Page_Load(object sender, EventArgs e)
      {
            //i would just call it like this
            string pass = GetRandomPasswordUsingGUID(10);
      }
}

It does what i want but there is a "Base" keyword that deals with base class in c# ... I really want to know when should use base keyword in my derived class....

Any good example...


Solution

The base keyword is used to refer to the base class when chaining constructors or when you want to access a member (method, property, anything) in the base class that has been overridden or hidden in the current class. For example,

class A {
    protected virtual void Foo() {
        Console.WriteLine("I'm A");
    }
}

class B : A {
    protected override void Foo() {
        Console.WriteLine("I'm B");
    }

    public void Bar() {
        Foo();
        base.Foo();
    }
}

With these definitions,

new B().Bar();

would output

I'm B
I'm A


Answered By - Matti Virkkunen
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, May 17, 2022

[FIXED] How to exclude a twig partial from a base extend in Symfony on some pages only?

 May 17, 2022     base, extend, partial, symfony, twig     No comments   

Issue

Is there a way to specify an "extend" in Twig to exclude one of its included partials ?

To better explain myself, here is my base.html.twig

<body>
        {% include '/main/_navbar.html.twig' %}
        {% block body %}
            {% for flashError in app.flashes('success') %}
                <div class="alert alert-success" role="alert">{{ message }}</div> 
            {% endfor %}
        {% endblock %}
        {% include '/main/_footer.html.twig' %}
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <script src="{{ asset('script/app.js') }}"></script>
    </body>

On my login page, I do not need my _navbar.html.twig partial. Is there a way to not include (exclude) it knowing my view extends from this base template ? Are there any "options" I could pass behind that extends ?

This is the code I use to extend my base template on my login page :

{% extends 'base.html.twig' %}

Solution

Just wrap the include you don't want to include in a seperate block, then override the block with empty content, e.g.

base.html.twig

<body>
        {% block nav %}
            {% include '/main/_navbar.html.twig' %}
        {% endblock %}
        {% block body %}
            {% for flashError in app.flashes('success') %}
                <div class="alert alert-success" role="alert">{{ message }}</div> 
            {% endfor %}
        {% endblock %}
        {% include '/main/_footer.html.twig' %}
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <script src="{{ asset('script/app.js') }}"></script>
</body>

login.html.twig

{% extends "base.html.twig" %}
{% block nav %}{% endblock %}

demo



Answered By - DarkBee
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, January 6, 2022

[FIXED] Session data ci3 base controller

 January 06, 2022     base, codeigniter, controller, php, session     No comments   

Issue

I have this on my controller named pages(i use it as a terminal to branch out to all views)

class pages extends MY_Controller 
{
    public function verification()
    {
        $session_data = $this->is_logged_in();

        print_r($session_data);

        if($this->is_logged_in())
        {

        }
    }
}

As you can see, i have a line 'print_r' on the session_data, i got some results the problem is it always returns only '1'.

This is the function on my base controller.

class MY_Controller extends CI_Controller 
{
    public function __construct()
    {
        parent::__construct();
    }
    
    public function is_logged_in()
    {
        $user = $this->session->userdata();
        return isset($user);
    }  
}

And this is the code block after logging in creating the session data on my authenticator controller.

Class user_authentication extends MY_Controller 
{
    public function register()
    {
        $this->form_validation->set_rules('username', 'Username','required|trim|min_length[8]|max_length[24]|is_unique[user.username]', [
            'required' => 'You have not provided %s.', 
            'is_unique' => 'This %s already exists.'
        ]);    
        $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[8]|max_length[16]');
        $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|min_length[6]|max_length[30]|is_unique[user.email]', [
            'required' => 'You have not provided %s. ', 
            'is_unique' => 'This %s already exists.'
        ]);
            $this->form_validation->set_rules('type', 'Account Type', 'trim|required|min_length[1]|max_length[1]', [
            'required' => 'please select: 1 - normal, 2 - trainer'
        ]);
        
        $this->form_validation->set_error_delimiters('', '');

        if ($this->form_validation->run() == FALSE)
        {
            $this->load->view('templates/header');
            $this->load->view('templates/navigation');
            $this->load->view('pages/login');
            $this->load->view('templates/footer');
        }
        else
        {
            $data = [
                'username' => $this->input->post('username'),
                'password' => $this->input->post('password'),
                'email' => $this->input->post('email'),
                'type' => $this->input->post('type'),
            ]; 
            
            $result = $this->Account_model->create_account($data);

            if($result == true)
            {
                $data['message_display'] = 'Registration Successful';

                $this->load->view('templates/header');
                $this->load->view('templates/navigation');
                $this->load->view('pages/homepage',$data);
                $this->load->view('templates/footer');    
            }
            else
            {
                $data['message_display'] = 'Username and/or Email already exists';

                $this->load->view('templates/header');
                $this->load->view('templates/navigation');
                $this->load->view('pages/login',$data);
                $this->load->view('templates/footer');
            }
        }
    }
    
    public function login()
    {
        $this->form_validation->set_rules('username', 'Username', 'required|trim|min_length[8]|max_length[24]');
        $this->form_validation->set_rules('password', 'Password', 'required|trim|min_length[8]|max_length[16]');

        if($this->form_validation->run() == FALSE)
        {
            $this->load->view('templates/header');
            $this->load->view('templates/navigation');
            $this->load->view('pages/login');
            $this->load->view('templates/footer');
        }
        else
        {
            $data = [
                'username' => $this->input->post('username'), 
                'password' => $this->input->post('password')
            ];
            $result = $this->Account_model->login_account($data);
            
            $this->session->set_userdata('isloggedin', [
                'username' => $result['username'], 
                'email' => $result['email'], 
                'type' => $result['type']
            ]);

            $data['title'] = 'home';

            $this->load->view('templates/header');
            $this->load->view('templates/navigation');
            $this->load->view('pages/home');
            $this->load->view('templates/footer');
        }
    }
}

There are some stuff that are basically useless as of right now but i'm putting them there for future uses. like the $data['title'] gonna use it as a placeholder for the title on the head of each view since i am using templates.

Am i doing something wrong? Why does when i print_r the session data from MY_Controller it only returns '1'.

I've been looking at guides but most of them are outdated and i am probably using deprecated stuff from past versions, if so kindly point them out, i want to practice coding neat and clean.


Solution

Your approach won't work that way because userdata returns an array with at least one key called __ci_last_regenerate (i'm not sure which CI version you use but if you autoload the session library you would always get an result here)

Set an extra key isLoggedin and you'll be fine.

Your login function:

public function login()
{
    $this->form_validation->set_rules('username', 'Username', 'required|trim|min_length[8]|max_length[24]');
    $this->form_validation->set_rules('password', 'Password', 'required|trim|min_length[8]|max_length[16]');
    if($this->form_validation->run() == FALSE)
    {
        $this->load->view('templates/header');
        $this->load->view('templates/navigation');
        $this->load->view('pages/login');
        $this->load->view('templates/footer');}
    else
    {
        $data = array('username' => $this->input->post('username'), 'password' => $this->input->post('password'));
        $result = $this->Account_model->login_account($data);

        if ($result)
        {
            $session_data = array('username' => $result['username'], 'email' => $result['email'], 'type' => $result['type'], 'isLoggedin' => true);
            $this->session->set_userdata($session_data);

            $data['title'] = 'home';
            $this->load->view('templates/header');
            $this->load->view('templates/navigation');
            $this->load->view('pages/home');
            $this->load->view('templates/footer');

        }

    }
}

and your controller

class MY_Controller extends CI_Controller {
    public function __construct()
    {
        parent::__construct();
    }

    public function is_logged_in()
    {
        return $this->session->userdata('isLoggedin');
    }  
}

With this approach you get either a correct value or NULL which returns true or false;

For more information you can take a look here https://codeigniter.com/userguide3/libraries/sessions.html#CI_Session::userdata



Answered By - sintakonte
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing