Calculating Colour Contrast for ASP - php

I found this code snippet for PHP and Javascript, but I was wondering if it could be made work in classic asp? Here's a whole article on the topic for reference.
http://24ways.org/2010/calculating-color-contrast/
PHP code
function getContrast50($hexcolor){
return (hexdec($hexcolor) > 0xffffff/2) ? 'black':'white';
}

Well, nothing built into the language. Converting hex to decimal is as easy as CLng("&H" & hexValue) but from quick look in the PHP manual I saw that hexdec() method ignores any invalid characters, while the VBScript CLng() will just crash.
So here is a working function that as far as I can tell doing the same thing:
Function GetContrast50(hexColor)
Const strValidChars = "1234567890abcdef"
Dim maxValue, decValue, sanitizedColor
Dim x, curChar
sanitizedColor = ""
For x=1 To Len(hexColor)
curChar = LCase(Mid(hexColor, x, 1))
If InStr(strValidChars, curChar)>0 Then
sanitizedColor = sanitizedColor & curChar
End If
Next
If Len(sanitizedColor)=0 Then
GetContrast50 = "invalid color string"
Exit Function
End If
maxValue = CLng("&H" & "ffffff")
decValue = CLng("&H" & sanitizedColor)
If decValue > (maxValue / 2) Then
GetContrast50 = "black"
Else
GetContrast50 = "white"
End If
End Function
It's pretty easy to extend the validation to check the given string is in valid range.

Related

What code it is and how to rewrite in php

i have got this code from one of api provider
Not sure its asp .net or something
Need to convert to php
i tried with some online tools, no luck.
Some One help what code it is and how i can convert to php.
string CrypCode = (DateTime.Now.Year.ToString()+ (Seed + DateTime.Now.DayOfYear.ToString()));
System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] bs = System.Text.Encoding.UTF8.GetBytes(CrypCode);
bs = x.ComputeHash(bs);
System.Text.StringBuilder s = new System.Text.StringBuilder();
foreach (byte b in bs)
{
s.Append(b.ToString("x2").ToLower());
}
string KEY = s.ToString();
return KEY;
I remember when i used to work with VB.NET. Hashing is headache. I see you are trying to md5 hash crypcode. In php its simple. Dont know why Microsoft languages long it out. They must have their reasons. Believe it or not in php its one line.
$crypcode = date("Y") + ($seed + date("z"));
$key = md5($crypcode);
return $key;
http://php.net/manual/en/function.md5.php
http://php.net/manual/en/function.date.php
https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.md5cryptoserviceprovider

Why use an anonymous function as a variable? [duplicate]

For a person without a comp-sci background, what is a lambda in the world of Computer Science?
Lambda comes from the Lambda Calculus and refers to anonymous functions in programming.
Why is this cool? It allows you to write quick throw away functions without naming them. It also provides a nice way to write closures. With that power you can do things like this.
Python
def adder(x):
return lambda y: x + y
add5 = adder(5)
add5(1)
6
As you can see from the snippet of Python, the function adder takes in an argument x, and returns an anonymous function, or lambda, that takes another argument y. That anonymous function allows you to create functions from functions. This is a simple example, but it should convey the power lambdas and closures have.
Examples in other languages
Perl 5
sub adder {
my ($x) = #_;
return sub {
my ($y) = #_;
$x + $y
}
}
my $add5 = adder(5);
print &$add5(1) == 6 ? "ok\n" : "not ok\n";
JavaScript
var adder = function (x) {
return function (y) {
return x + y;
};
};
add5 = adder(5);
add5(1) == 6
JavaScript (ES6)
const adder = x => y => x + y;
add5 = adder(5);
add5(1) == 6
Scheme
(define adder
(lambda (x)
(lambda (y)
(+ x y))))
(define add5
(adder 5))
(add5 1)
6
C# 3.5 or higher
Func<int, Func<int, int>> adder =
(int x) => (int y) => x + y; // `int` declarations optional
Func<int, int> add5 = adder(5);
var add6 = adder(6); // Using implicit typing
Debug.Assert(add5(1) == 6);
Debug.Assert(add6(-1) == 5);
// Closure example
int yEnclosed = 1;
Func<int, int> addWithClosure =
(x) => x + yEnclosed;
Debug.Assert(addWithClosure(2) == 3);
Swift
func adder(x: Int) -> (Int) -> Int{
return { y in x + y }
}
let add5 = adder(5)
add5(1)
6
PHP
$a = 1;
$b = 2;
$lambda = fn () => $a + $b;
echo $lambda();
Haskell
(\x y -> x + y)
Java see this post
// The following is an example of Predicate :
// a functional interface that takes an argument
// and returns a boolean primitive type.
Predicate<Integer> pred = x -> x % 2 == 0; // Tests if the parameter is even.
boolean result = pred.test(4); // true
Lua
adder = function(x)
return function(y)
return x + y
end
end
add5 = adder(5)
add5(1) == 6 -- true
Kotlin
val pred = { x: Int -> x % 2 == 0 }
val result = pred(4) // true
Ruby
Ruby is slightly different in that you cannot call a lambda using the exact same syntax as calling a function, but it still has lambdas.
def adder(x)
lambda { |y| x + y }
end
add5 = adder(5)
add5[1] == 6
Ruby being Ruby, there is a shorthand for lambdas, so you can define adder this way:
def adder(x)
-> y { x + y }
end
R
adder <- function(x) {
function(y) x + y
}
add5 <- adder(5)
add5(1)
#> [1] 6
A lambda is a type of function, defined inline. Along with a lambda you also usually have some kind of variable type that can hold a reference to a function, lambda or otherwise.
For instance, here's a C# piece of code that doesn't use a lambda:
public Int32 Add(Int32 a, Int32 b)
{
return a + b;
}
public Int32 Sub(Int32 a, Int32 b)
{
return a - b;
}
public delegate Int32 Op(Int32 a, Int32 b);
public void Calculator(Int32 a, Int32 b, Op op)
{
Console.WriteLine("Calculator: op(" + a + ", " + b + ") = " + op(a, b));
}
public void Test()
{
Calculator(10, 23, Add);
Calculator(10, 23, Sub);
}
This calls Calculator, passing along not just two numbers, but which method to call inside Calculator to obtain the results of the calculation.
In C# 2.0 we got anonymous methods, which shortens the above code to:
public delegate Int32 Op(Int32 a, Int32 b);
public void Calculator(Int32 a, Int32 b, Op op)
{
Console.WriteLine("Calculator: op(" + a + ", " + b + ") = " + op(a, b));
}
public void Test()
{
Calculator(10, 23, delegate(Int32 a, Int32 b)
{
return a + b;
});
Calculator(10, 23, delegate(Int32 a, Int32 b)
{
return a - b;
});
}
And then in C# 3.0 we got lambdas which makes the code even shorter:
public delegate Int32 Op(Int32 a, Int32 b);
public void Calculator(Int32 a, Int32 b, Op op)
{
Console.WriteLine("Calculator: op(" + a + ", " + b + ") = " + op(a, b));
}
public void Test()
{
Calculator(10, 23, (a, b) => a + b);
Calculator(10, 23, (a, b) => a - b);
}
The name "lambda" is just a historical artifact. All we're talking about is an expression whose value is a function.
A simple example (using Scala for the next line) is:
args.foreach(arg => println(arg))
where the argument to the foreach method is an expression for an anonymous function. The above line is more or less the same as writing something like this (not quite real code, but you'll get the idea):
void printThat(Object that) {
println(that)
}
...
args.foreach(printThat)
except that you don't need to bother with:
Declaring the function somewhere else (and having to look for it when you revisit the code later).
Naming something that you're only using once.
Once you're used to function values, having to do without them seems as silly as being required to name every expression, such as:
int tempVar = 2 * a + b
...
println(tempVar)
instead of just writing the expression where you need it:
println(2 * a + b)
The exact notation varies from language to language; Greek isn't always required! ;-)
It refers to lambda calculus, which is a formal system that just has lambda expressions, which represent a function that takes a function for its sole argument and returns a function. All functions in the lambda calculus are of that type, i.e., λ : λ → λ.
Lisp used the lambda concept to name its anonymous function literals. This lambda represents a function that takes two arguments, x and y, and returns their product:
(lambda (x y) (* x y))
It can be applied in-line like this (evaluates to 50):
((lambda (x y) (* x y)) 5 10)
The lambda calculus is a consistent mathematical theory of substitution. In school mathematics one sees for example x+y=5 paired with x−y=1. Along with ways to manipulate individual equations it's also possible to put the information from these two together, provided cross-equation substitutions are done logically. Lambda calculus codifies the correct way to do these substitutions.
Given that y = x−1 is a valid rearrangement of the second equation, this: λ y = x−1 means a function substituting the symbols x−1 for the symbol y. Now imagine applying λ y to each term in the first equation. If a term is y then perform the substitution; otherwise do nothing. If you do this out on paper you'll see how applying that λ y will make the first equation solvable.
That's an answer without any computer science or programming.
The simplest programming example I can think of comes from http://en.wikipedia.org/wiki/Joy_(programming_language)#How_it_works:
here is how the square function might be defined in an imperative
programming language (C):
int square(int x)
{
return x * x;
}
The variable x is a formal parameter which is replaced by the actual
value to be squared when the function is called. In a functional
language (Scheme) the same function would be defined:
(define square
(lambda (x)
(* x x)))
This is different in many ways, but it still uses the formal parameter
x in the same way.
Added: http://imgur.com/a/XBHub
Slightly oversimplified: a lambda function is one that can be passed round to other functions and it's logic accessed.
In C# lambda syntax is often compiled to simple methods in the same way as anonymous delegates, but it can also be broken down and its logic read.
For instance (in C#3):
LinqToSqlContext.Where(
row => row.FieldName > 15 );
LinqToSql can read that function (x > 15) and convert it to the actual SQL to execute using expression trees.
The statement above becomes:
select ... from [tablename]
where [FieldName] > 15 --this line was 'read' from the lambda function
This is different from normal methods or anonymous delegates (which are just compiler magic really) because they cannot be read.
Not all methods in C# that use lambda syntax can be compiled to expression trees (i.e. actual lambda functions). For instance:
LinqToSqlContext.Where(
row => SomeComplexCheck( row.FieldName ) );
Now the expression tree cannot be read - SomeComplexCheck cannot be broken down. The SQL statement will execute without the where, and every row in the data will be put through SomeComplexCheck.
Lambda functions should not be confused with anonymous methods. For instance:
LinqToSqlContext.Where(
delegate ( DataRow row ) {
return row.FieldName > 15;
} );
This also has an 'inline' function, but this time it's just compiler magic - the C# compiler will split this out to a new instance method with an autogenerated name.
Anonymous methods can't be read, and so the logic can't be translated out as it can for lambda functions.
The question is formally answered greatly, so I will not try to add more on this.
In very simple, informal words to someone that knows very little or nothing on math or programming, I would explain it as a small "machine" or "box" that takes some input, makes some work and produces some output, has no particular name, but we know where it is and by just this knowledge, we use it.
Practically speaking, for a person that knows what a function is, I would tell them that it is a function that has no name, usually put to a point in memory that can be used just by referencing to that memory (usually via the usage of a variable - if they have heard about the concept of the function pointers, I would use them as a similar concept) - this answer covers the pretty basics (no mention of closures etc) but one can get the point easily.
I like the explanation of Lambdas in this article: The Evolution Of LINQ And Its Impact On The Design Of C#. It made a lot of sense to me as it shows a real world for Lambdas and builds it out as a practical example.
Their quick explanation: Lambdas are a way to treat code (functions) as data.
A Lambda Function, or a Small Anonymous Function, is a self-contained block of functionality that can be passed around and used in your code. Lambda has different names in different programming languages – Lambda in Python and Kotlin, Closure in Swift, or Block in C and Objective-C. Although lambda's meaning is quite similar for these languages it has slight distinctions sometimes.
Let's see how Closure (Lambda) works in Swift:
let coffee: [String] = ["Cappuccino", "Espresso", "Latte", "Ristretto"]
1. Regular Function
func backward(_ n1: String, _ n2: String) -> Bool {
return n1 > n2
}
var reverseOrder = coffee.sorted(by: backward)
// RESULT: ["Ristretto", "Latte", "Espresso", "Cappuccino"]
2. Closure Expression
reverseOrder = coffee.sorted(by: { (n1: String, n2: String) -> Bool in
return n1 > n2
})
3. Inline Closure Expression
reverseOrder = coffee.sorted(by: { (n1: String, n2: String) -> Bool in
return n1 > n2
})
4. Inferring Type From Context
reverseOrder = coffee.sorted(by: { n1, n2 in return n1 > n2 } )
5. Implicit Returns from Single-Expression Closures
reverseOrder = coffee.sorted(by: { n1, n2 in n1 > n2 } )
6. Shorthand Argument Names
reverseOrder = coffee.sorted(by: { $0 > $1 } )
// $0 and $1 are closure’s first and second String arguments.
7. Operator Methods
reverseOrder = coffee.sorted(by: >)
// RESULT: ["Ristretto", "Latte", "Espresso", "Cappuccino"]
#Brian I use lambdas all the time in C#, in LINQ and non-LINQ operators. Example:
string[] GetCustomerNames(IEnumerable<Customer> customers)
{ return customers.Select(c=>c.Name);
}
Before C#, I used anonymous functions in JavaScript for callbacks to AJAX functions, before the term Ajax was even coined:
getXmlFromServer(function(result) {/*success*/}, function(error){/*fail*/});
The interesting thing with C#'s lambda syntax, though, is that on their own their type cannot be infered (i.e., you can't type var foo = (x,y) => x * y) but depending on which type they're assigned to, they'll be compiled as delegates or abstract syntax trees representing the expression (which is how LINQ object mappers do their "language-integrated" magic).
Lambdas in LISP can also be passed to a quotation operator and then traversed as a list of lists. Some powerful macros are made this way.
An example of a lambda in Ruby is as follows:
hello = lambda do
puts('Hello')
puts('I am inside a proc')
end
hello.call
Will genereate the following output:
Hello
I am inside a proc
Just because I cant see a C++11 example here, I'll go ahead and post this nice example from here. After searching, it is the clearest language specific example that I could find.
Hello, Lambdas, version 1
template<typename F>
void Eval( const F& f ) {
    f();
}
void foo() {
    Eval( []{ printf("Hello, Lambdas\n"); } );
}
Hello, Lambdas, version 2:
void bar() {
    auto f = []{ printf("Hello, Lambdas\n"); };
    f();
}
For a person without a comp-sci background, what is a lambda in the world of Computer Science?
I will illustrate it intuitively step by step in simple and readable python codes.
In short, a lambda is just an anonymous and inline function.
Let's start from assignment to understand lambdas as a freshman with background of basic arithmetic.
The blueprint of assignment is 'the name = value', see:
In [1]: x = 1
...: y = 'value'
In [2]: x
Out[2]: 1
In [3]: y
Out[3]: 'value'
'x', 'y' are names and 1, 'value' are values.
Try a function in mathematics
In [4]: m = n**2 + 2*n + 1
NameError: name 'n' is not defined
Error reports,
you cannot write a mathematic directly as code,'n' should be defined or be assigned to a value.
In [8]: n = 3.14
In [9]: m = n**2 + 2*n + 1
In [10]: m
Out[10]: 17.1396
It works now,what if you insist on combining the two seperarte lines to one.
There comes lambda
In [13]: j = lambda i: i**2 + 2*i + 1
In [14]: j
Out[14]: <function __main__.<lambda>>
No errors reported.
This is a glance at lambda, it enables you to write a function in a single line as you do in mathematic into the computer directly.
We will see it later.
Let's continue on digging deeper on 'assignment'.
As illustrated above, the equals symbol = works for simple data(1 and 'value') type and simple expression(n**2 + 2*n + 1).
Try this:
In [15]: x = print('This is a x')
This is a x
In [16]: x
In [17]: x = input('Enter a x: ')
Enter a x: x
It works for simple statements,there's 11 types of them in python 7. Simple statements — Python 3.6.3 documentation
How about compound statement,
In [18]: m = n**2 + 2*n + 1 if n > 0
SyntaxError: invalid syntax
#or
In [19]: m = n**2 + 2*n + 1, if n > 0
SyntaxError: invalid syntax
There comes def enable it working
In [23]: def m(n):
...: if n > 0:
...: return n**2 + 2*n + 1
...:
In [24]: m(2)
Out[24]: 9
Tada, analyse it, 'm' is name, 'n**2 + 2*n + 1' is value.: is a variant of '='.
Find it, if just for understanding, everything starts from assignment and everything is assignment.
Now return to lambda, we have a function named 'm'
Try:
In [28]: m = m(3)
In [29]: m
Out[29]: 16
There are two names of 'm' here, function m already has a name, duplicated.
It's formatting like:
In [27]: m = def m(n):
...: if n > 0:
...: return n**2 + 2*n + 1
SyntaxError: invalid syntax
It's not a smart strategy, so error reports
We have to delete one of them,set a function without a name.
m = lambda n:n**2 + 2*n + 1
It's called 'anonymous function'
In conclusion,
lambda in an inline function which enable you to write a function in one straight line as does in mathematics
lambda is anonymous
Hope, this helps.
Lambda explained for everyone:
Lambda is an anonymous function. This means lambda is a function object in Python that doesn't require a reference before. Let's consider this bit of code here:
def name_of_func():
#command/instruction
print('hello')
print(type(name_of_func)) #the name of the function is a reference
#the reference contains a function Object with command/instruction
To proof my proposition I print out the type of name_of_func which returns us:
<class 'function'>
A function must have a interface, but a interface docent needs to contain something. What does this mean? Let's look a little bit closer to our function and we may notice that out of the name of the functions there are some more details we need to explain to understand what a function is.
A regular function will be defined with the syntax "def", then we type in the name and settle the interface with "()" and ending our definition by the syntax ":". Now we enter the functions body with our instructions/commands.
So let's consider this bit of code here:
def print_my_argument(x):
print(x)
print_my_argument('Hello')
In this case we run our function, named "print_my_argument" and passing a parameter/argument through the interface. The Output will be:
Hello
So now that we know what a function is and how the architecture works for a function, we can take a look to an anonymous function. Let's consider this bit of code here:
def name_of_func():
print('Hello')
lambda: print('Hello')
these function objects are pretty much the same except of the fact that the upper, regular function have a name and the other function is an anonymous one. Let's take a closer look on our anonymous function, to understand how to use it.
So let's consider this bit of code here:
def delete_last_char(arg1=None):
print(arg1[:-1])
string = 'Hello World'
delete_last_char(string)
f = lambda arg1=None: print(arg1[:-1])
f(string)
So what we have done in the above code is to write once again, a regular function and an anonymous function. Our anonymous function we had assigned to a var, which is pretty much the same as to give this function a name. Anyway, the output will be:
Hello Worl
Hello Worl
To fully proof that lambda is a function object and doesn't just mimic a function we run this bit of code here:
string = 'Hello World'
f = lambda arg1=string: print(arg1[:-1])
f()
print(type(f))
and the Output will be:
Hello Worl
<class 'function'>
Last but not least you should know that every function in python needs to return something. If nothing is defined in the body of the function, None will be returned by default. look at this bit of code here:
def delete_last_char(arg1):
print(arg1[:-1])
string = 'Hello World'
x = delete_last_char(string)
f = lambda arg1=string: print(arg1[:-1])
x2 = f()
print(x)
print(x2)
Output will be:
Hello Worl
Hello Worl
None
None
You can think of it as an anonymous function - here's some more info: Wikipedia - Anonymous Function
I have trouble wrapping my head around lambda expressions because I work in Visual FoxPro, which has Macro substitution and the ExecScript{} and Evaluate() functions, which seem to serve much the same purpose.
? Calculator(10, 23, "a + b")
? Calculator(10, 23, "a - b");
FUNCTION Calculator(a, b, op)
RETURN Evaluate(op)
One definite benefit to using formal lambdas is (I assume) compile-time checking: Fox won't know if you typo the text string above until it tries to run it.
This is also useful for data-driven code: you can store entire routines in memo fields in the database and then just evaluate them at run-time. This lets you tweak part of the application without actually having access to the source. (But that's another topic altogether.)
It is a function that has no name. For e.g. in c# you can use
numberCollection.GetMatchingItems<int>(number => number > 5);
to return the numbers that are greater than 5.
number => number > 5
is the lambda part here. It represents a function which takes a parameter (number) and returns a boolean value (number > 5). GetMatchingItems method uses this lambda on all the items in the collection and returns the matching items.
In Javascript, for example, functions are treated as the same mixed type as everything else (int, string, float, bool). As such, you can create functions on the fly, assign them to things, and call them back later. It's useful but, not something you want to over use or you'll confuse everyone who has to maintain your code after you...
This is some code I was playing with to see how deep this rabbit hole goes:
var x = new Object;
x.thingy = new Array();
x.thingy[0] = function(){ return function(){ return function(){ alert('index 0 pressed'); }; }; }
x.thingy[1] = function(){ return function(){ return function(){ alert('index 1 pressed'); }; }; }
x.thingy[2] = function(){ return function(){ return function(){ alert('index 2 pressed'); }; }; }
for(var i=0 ;i<3; i++)
x.thingy[i]()()();
In context of CS a lambda function is an abstract mathematical concept that tackles a problem of symbolic evaluation of mathematical expressions. In that context a lambda function is the same as a lambda term.
But in programming languages it's something different. It's a piece of code that is declared "in place", and that can be passed around as a "first-class citizen". This concept appeared to be useful so that it came into almost all popular modern programming languages (see lambda functions everwhere post).
In computer programming, lambda is a piece of code (statement, expression or a group of them) which takes some arguments from an external source. It must not always be an anonymous function - we have many ways to implement them.
We have clear separation between expressions, statements and functions, which mathematicians do not have.
The word "function" in programming is also different - we have "function is a series of steps to do" (from Latin "perform"). In math it is something about correlation between variables.
Functional languages are trying to be as similar to math formulas as possible, and their words mean almost the same. But in other programming languages we have it different.
The question has been answered fully, I don't want to go into details. I want to share the usage when writing numerical computation in rust.
There is an example of a lambda(anonymous function)
let f = |x: f32| -> f32 { x * x - 2.0 };
let df = |x: f32| -> f32 { 2.0 * x };
When I was writing a module of Newton–Raphson method, it was used as first and second order derivative. (If you want to know what is Newton–Raphson method, please visit "https://en.wikipedia.org/wiki/Newton%27s_method".
The output as the following
println!("f={:.6} df={:.6}", f(10.0), df(10.0))
f=98.000000 df=20.000000
Imagine that you have a restaurant with a delivery option and you have an order that needs to be done in under 30 minutes. The point is clients usually don't care if you send their food by bike with a car or barefoot as long as you keep the meal warm and tied up. So lets convert this idiom to Javascript with anonymous and defined transportation functions.
Below we defined the way of our delivering aka we define a name to a function:
// ES5
var food = function withBike(kebap, coke) {
return (kebap + coke);
};
What if we would use arrow/lambda functions to accomplish this transfer:
// ES6
const food = (kebap, coke) => { return kebap + coke };
You see there is no difference for client and no time wasting to think about how to send food. Just send it.
Btw, I don't recommend the kebap with coke this is why upper codes will give you errors. Have fun.
A lambda function can take any number of arguments, but they contain only a single expression. ...
Lambda functions can be used to return function objects.
Syntactically, lambda functions are restricted to only a single expression.

Get negative numbers after conversion to float [duplicate]

I am trying to convert a hex string into a signed integer.
I am able to easily transfer it into an unsigned value with hexdec() but this does not give a signed value.
Edit:
code in VB - the two "AA" hex values are representative.
Dim bs(2) As Byte
bs(1) = "AA"
bs(2) = "AA"
Dim s As Short
s = BitConverter.ToInt16(bs, 1)
Check out this comment via php.net:
hexdec() returns unsigned integers. For example hexdec("FFFFFFFE") returns 4294967294, not -2. To convert to signed 32-bit integer you may do:
<?php
echo reset(unpack("l", pack("l", hexdec("FFFFFFFE"))));
?>
As said on the hexdec manual page :
The function can now convert values
that are to big for the platforms
integer type, it will return the value
as float instead in that case.
If you want to get some kind of big integer (not float), you'll need it stored inside a string... This might be possible using BC Math functions.
For instance, if you look in the comments of the hexdec manual page, you'll find this note
If you adapt that function a bit, to avoid a notice, you'll get :
function bchexdec($hex)
{
$dec = 0;
$len = strlen($hex);
for ($i = 1; $i <= $len; $i++) {
$dec = bcadd($dec, bcmul(strval(hexdec($hex[$i - 1])), bcpow('16', strval($len - $i))));
}
return $dec;
}
(This function has be copied from the note I linked to ; and only a bit adapted by me)
And using it on your number :
$h = 'D5CE3E462533364B';
$f = bchexdec($h);
var_dump($f);
The output will be :
string '15406319846273791563' (length=20)
So, not the kind of big float you had ; and seems OK with what you are expecting :
Result from calc.exe =
15406319846273791563
Hope this help ;-)
And, yes, user notes on the PHP documentation are sometimes a real gold mine ;-)
I've been trying to find a decent answer to this question and so I wrote this function which works well for a Hex string input, returning a signed decimal value.
public function hex_to_signed_int($hex_str){
$dec = hexdec($hex_str);
//test is value negative
if($dec & pow(16,strlen($hex_str))/2 ){ return $dec-pow(16,strlen($hex_str));}
return $dec;
}

Same algorithm runs differently in C and PHP

I was practicing a problem on CodeChef.com.
https://www.codechef.com/problems/CHOPRT --> Link to the question I was solving.
I successfully solved the question using C.
My C code:
#include <stdio.h>
int main() {
int t;
int num1;
int num2;
scanf("%d", &t);
while(t--) {
scanf("%d %d", &num1, &num2);
if(num1 > num2)
printf(">");
else if(num1 < num2)
printf("<");
else
printf("=");
printf("\n");
}
return 0;
}
But I am not able to solve it using PHP:
My PHP code:
<?php
$t = intval(fgets(STDIN));
while($t--) {
$line = split(" ", trim(fgets(STDIN)));
$num1 = intval($line[0]);
$num2 = intval($line[1]);
if($num1 < $num2)
print("<");
else if($num1 > $num2)
print(">");
else
print("=");
print("\n");
}
?>
Though both the programs run perfectly on my MacBook Pro, the PHP code is not run on codechef.com and gives a WA(Wrong Answer). C code is run perfectly though and that to within 0.00 seconds.
Please, enlighten me with the difference between the two respective codes, which I personally believe, should be working the same, and also produce the same output.
Often i hear that some testcases are erroneous.I have a corner case for you which would give perfect result for your C code but not for your PHP
Do this :
1
10 10
Notice there is more than one space between the two digits.
I tested it here.
Instead of the expected output which is:
=
your Output is:
>
Though C would pass this test case as scanf searches for the next integer number you type, PHP would fail since there is more than one space.
To make it work in PHP i did suggest you to code in such a way that the spaces between the two numbers dont affect your expected output.
That's the only way i believe your PHP Code won't work.If this indeed was the issue it's not your fault!

send PHP string to C++

I am trying to pass over from php a string into C++, i managed to figure out how to pass numbers, but it doesn't work for letters. Here's what i have that works for PHP
<?php
$r = 5;
$s = 12;
$x= 3;
$y= 4;
$q= "Hello World";
$c_output=`project1.exe $r $s $x $y $q`; // pass in the value to the c++ prog
echo "<pre>$c_output</pre>"; //received the sum
//modify the value in php and output
echo "output from C++ programm is" . ($c_output + 1);
?>
This sends the variables r,s,x,y, and q to the C++ programm project1.exe and IT WORKS, but the problem is that it doesn't work for the string variable $q.
Here's the code that I have in my C++ programm, it's simple:
#include<iostream>
#include<cstdlib>
#include<string>
using namespace std;
int main(int in, char* argv[]) {
int val[2];
for(int i = 1; i < in; i++) { // retrieve the value from php
val[i-1] = atoi(argv[i]);
}
double r = val[0];
double s = val[1];
double x = val[2];
double y = val[3];
double q = val[4]; // here's the problem, as soon as i try to define val[4] as a string or char, it screws up
cout << r;
cout <<s;
cout << x;
cout << y;
cout << q;
// will output to php
return 0;
}
It works, but for the string "Hello world" which i pass through $q from PHP doesn't give me the string back (i know it's defined as a double, but as soon as i try to change it to a string or a char variable the code just doesn't compile).
Please explain to me how i have to go around this problem so that $q can be processed as a string. FYI, I am a newbie to programming (6 months in).
Try not converting the final argument using atoi(argv[i]). Just keep it as argv[i].
for(int i = 1; i < in-1; i++)
{
val[i-1] = atoi(argv[i]);
}
q = argv[i];
It doesn't work for letters because you are doing atoi(..)(which converts char-string to integer) in the C++ program.
Have some means of letting the program know what to expect -- whether a number or a string. May be the first argument can help the program differentiate, like may be the following:
$c_output = `project1.exe nnsnns 1 2 string1 3 4 string2`
Then you could do:
for(int i = 0/*NOTE*/,len=strlen(argv[1]); i < len; i++) { // retrieve the value from php
if (argv[1][i] == 'n'){
//argv[2+i] must be an integer
}else if (argv[1][i] == 's'){
//argv[2+i] is a string
}
}
Of course you should check if (strlen(argv[1]) == in-2).
BTW, in the C++ code above, val is a array holding 2 ints; and you are trying to access much beyond index 1.
To pass one single string to the C++ you would do something like the following:
$output = `project1.exe $q`; //Read below.
NOTE: $q must be a single word. No spaces, no extra characters like '|', '&', or any other character which the shell might interpret differently. $q must be clean before you pass that on to C++ Program. If $q is more than one word, use quotes.
C++ Part (Just try the following, then you can modify as you go along)
cout<<argv[1]<<endl;

Categories