문제

I can do this:

int main(int argc, char** argv) {
  unsigned char cTest = 0xff;
  return 0;
}

But what's the right way to get a hexadecimal number into the program via the command line?

unsigned char cTest = argv[1];

doesn't do the trick. That produces a initialization makes integer from pointer without a cast warning.

도움이 되었습니까?

해결책

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
  printf("%ld\n", strtol(argv[1], NULL, 16));

  return 0;
}

Example usage:

$ ./hex ff
255

다른 팁

I think some people arriving here might just be looking for:

$ ./prog `python -c 'print "\x41\x42\x43"'`
$ ./prog `perl -e 'print "\x41\x42\x43"'`
$ ./prog `ruby -e 'print "\x41\x42\x43"'`

예, 단순한 Ajax 요청을 수행하십시오.jQuery와 함께 :

$("#formid").submit(function(){
   $.ajax({
      type: "POST",
      url: "someFileToUpdateTheSession.php",
      data: $(this).serialize(),
      success: function(){
          // Do what you want to do when the session has been updated
      }
   });

   return false;
});
.

및 PHP :

<?php
   session_start();
   $_SESSION["name"] = $_POST["name"];
   // Add the rest of the post-variables to session-variables in the same manner
?>
.

메모

입력 필드에 이름 속성을 추가해야합니다.

unsigned char cTest = argv[1];

is wrong, because argv[1] is of type char *. If argv[1] contains something like "0xff" and you want to assign the integer value corresponding to that to an unsigned char, the easiest way would be probably to use strtoul() to first convert it to an unsigned long, and then check to see if the converted value is less than or equal to UCHAR_MAX. If yes, you can just assign to cTest.

strtoul()'s third parameter is a base, which can be 0 to denote C-style number parsing (octal and hexadecimal literals are allowed). If you only want to allow base 16, pass that as the third argument to strtoul(). If you want to allow any base (so you can parse 0xff, 0377, 255, etc.), use 0.

UCHAR_MAX is defined in <limits.h>.

The traditional way to do this kind of thing in C is with scanf(). It's exactly the inverse of printf(), reading the given format out of the file (or terminal) and into the variables you list, rather than writing them into it.

In your case, you'd use sscanf as you've already got it in a string rather than a stream.

atoi, atol, strtoi, strtol

all in stdlib.h

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top