翻同事的The C Programming Language 2th(C程序设计语言)和对应的习题解答The C Answer Book看到的。
实体书看得爽,但写文章还是得找电子版,英文的chm有,可惜习题解答没文字版……
The shift operators < < and >> perform left and right shifts of their left operand by the number of bit positions given by the right operand, which must be non-negative. Thus x < < 2 shifts the value of x by two positions, filling vacated bits with zero; this is equivalent to multiplication by 4. Right shifting an unsigned quantity always fits the vacated bits with zero. Right shifting a signed quantity will fill with bit signs (``arithmetic shift'') on some machines and with 0-bits (``logical shift'') on others.
The unary operator ~ yields the one’s complement of an integer; that is, it converts each 1-bit into a 0-bit and vice versa. For example
sets the last six bits of x to zero. Note that x & ~077 is independent of word length, and is thus preferable to, for example, x & 0177700, which assumes that x is a 16-bit quantity. The portable form involves no extra cost, since ~077 is a constant expression that can be evaluated at compile time.
As an illustration of some of the bit operators, consider the function getbits(x,p,n) that returns the (right adjusted) n-bit field of x that begins at position p. We assume that bit position 0 is at the right end and that n and p are sensible positive values. For example, getbits(x,4,3) returns the three bits in positions 4, 3 and 2, right-adjusted.
/* getbits: get n bits from position p */
unsigned getbits(unsigned x, int p, int n)
{
return (x >> (p+1-n)) & ~(~0 < < n);
}
The expression x >> (p+1-n) moves the desired field to the right end of the word. ~0 is all 1-bits; shifting it left n positions with ~0< places zeros in the rightmost n bits; complementing that with ~ makes a mask with ones in the rightmost n bits.
Exercise 2-6. Write a function setbits(x,p,n,y) that returns x with the n bits that begin at position p set to the rightmost n bits of y, leaving the other bits unchanged.
unsigned setbits(unsigned x, int p, int n, unsigned y)
{
return (x & ((~0 < < (p + 1)) | (~(~0 << (p + 1 - n))))) | ((y & ~(~0 << n)) << (p + 1 - n));
}
下面这个比较快:
unsigned setbits(unsigned x, int p, int n, unsigned y)
{
return x & ~(~(~0 < < n) << (p+1-n)) |
(y & ~(~0 << n)) << (p+1-n));
}
阅读全文...
http://live.aulddays.com/tech/10/double-float-ind-nan-inf/
打印浮点数输出 1.#IND 1.#INF nan inf 等解决
2010-03-11 11:24:34 旧日重来
进行浮点数编程时,如果没有注意,常常会出现输出类似 1.#IND, 1.#INF 或者 nan, inf 之类奇怪的输出。这通常隐含了浮点数操作的异常。
阅读全文…
http://www.gnu.org/s/libc/manual/html_node/Line-Input.html
12.9 Line-Oriented Input
Since many programs interpret input on the basis of lines, it is convenient to have functions to read a line of text from a stream.
Standard C has functions to do this, but they aren’t very safe: null characters and even (for gets) long lines can confuse them. So the GNU library provides the nonstandard getline function that makes it easy to read lines reliably.
Another GNU extension, getdelim, generalizes getline. It reads a delimited record, defined as everything through the next occurrence of a specified delimiter character.
All these functions are declared in stdio.h.
#define _GNU_SOURCE // 没这个编译时会有warning, 详见下文
#include <stdio .h>
ssize_t getline(char **lineptr, size_t *n, FILE *stream);
ssize_t getdelim(char **lineptr, size_t *n, int delim, FILE *stream);
</stdio>
读到的字符串,当然也是包括结尾的\n的;行末没\n的也不会加\n。delim也是类似。
阅读全文…
http://stackoverflow.com/questions/137038/how-do-you-get-assembler-output-from-c-c-source-in-gcc
http://www.delorie.com/djgpp/v2faq/faq8_20.html
http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html#s3
gcc -S -o my_asm_output.s helloworld.c
gcc -c -g -Wa,-a,-ad [other GCC options] foo.c > foo.lst
file helloworld
objdump -s --disassemble helloworld > helloworld.dump
-masm=dialect
Output asm instructions using selected dialect. Supported choices
are intel or att (the default one).
阅读全文…
目前只小程序,暂时先关心C下的。
TRE基本就是把GNU C library那个给抠出来了,能查找匹配的起止位置。说简单还是要自己写代码取具体字符,感觉用处不大。
PCRE是Perl Compatible Regular Expressions,功能上比较接近Perl的,作为Perl程序员,首选之。
regex嘛,不知道……
看到2008年的alpha就懒得试。难道已经终止开发了?
C++下有个专用的:
boost
Linux下搞C++不用boost,那基本就白活了,大概……
我可没说C++下不能用PCRE。
http://www.dmoz.org/Computers/Programming/Languages/Regular_Expressions/C_and_C%2b%2b/
- C++ Regular Expression Library – A free component that enables the use of regular expression searching in a C++ program.
- Grammar to parser classes – C++ template classes for declaring grammars directly in the code as set of compound classes. Includes regexp_parser class for parsing input upon regular expression definition provided in its constructor.
- Oniguruma – A C regular expression library, developed for the programming language Ruby. Provides software-download, description, links and references.
- PCRE – Perl Compatible Regular Expressions – A C library for matching regular expressions with Perl 5 syntax and semantics. PCRE has its own native API, as well as a set of wrapper functions that correspond to the POSIX regular expression API.
- PCRE Win32 – Provides compile PCRE libraries for Windows developers, and source code to build with Visual C++.
- regex – A modified version of Henry Spencer’s regular expression library (Autoconf, Automake and Libtool scripts have been added and a few file names have been changed). Also related links.
- TRE – Lightweight, robust, and almost fully POSIX compliant regexp matching library which supports approximate matches. [GNU GPL].
- xpressive – A C++ regex template library that allows regexes to be written as strings or as expression templates and to refer to themselves and other regexes recursively.
- Text processing for C/C++ programmers – John Maddock, the author of RegEx++, explains how to use Regular Expressions in C/C++ programs. (October 1, 2001)
阅读全文…
http://hi.baidu.com/pigfanfan/blog/item/e4f884a4e9484ef09152ee42.html
Static library & dynamic library — linux系统下的静态库与动态库
2008-12-01 18:17
写这篇文章主要是由于昨天心心同学问了个关于实现动态库链接的makefile。然后我囧了,没能解答=,=
然后今天把《Advanced Linux Programming》看了下,把笔记写下来。。。
难免回有错误,还忘不吝指正:)
我们知道,几乎所有的程序在运行时都会链接到一个或多个库。比如C语言的printf函数,调用此函数时就会用到c的标准输入输出库;而在GUI下面,会用到对应的图形库;调用数据库时,会用到数据库系统提供的相应的库,等等。
补充:objdump可以查看些信息。
阅读全文…
Fun with NULL pointers
http://lwn.net/Articles/342330/
http://lwn.net/Articles/342420/
[译文] 空指针的乐趣
http://labs.chinamobile.com/mblog/225_26068
http://labs.chinamobile.com/mblog/225_26884
作者:Jonathan Corbet
原文发布日期:July 20, 2009
来源:http://lwn.net/Articles/342330/
译者:王旭 ( http://wangxu.me , @gnawux )
现在,大部分读者都已经知道了 Brad Spengler 发布的“the local kernel exploit”(本地内核漏洞利用)。这一漏洞会影响 2.6.30 内核(以及 RHEL5的一个测试版 2.6.18 内核),受到了多方关注。本文将详细分析如何利用这一漏洞,以及让这个漏洞得以成真的令人震惊的一连串错误。
阅读全文…
http://u2.dmhy.org/forums.php?action=viewtopic&topicid=1264
http://u2.dmhy.org/forums.php?action=viewtopic&topicid=1274
解析torrent的源代碼:
013231原創,u2.dmhy.org首發,轉載或使用需注明出處.
[Torrent.cs]
//013231原創,u2.dmhy.org首發,轉載或使用需注明出處.
class Torrent
{
public Torrent(string filename)
{
this.filename = filename;
using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
bencodeArray = new byte[fs.Length];
fs.Read(bencodeArray, 0, (int)fs.Length);
}
curIndex = 0;
rootDictionary = scan() as Dictionary<string ,object>;
files = getFiles();
}
object scan()
{
switch ((char)bencodeArray[curIndex])
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return string_b();
case 'i':
return integer_b();
case 'l':
return list_b();
case 'd':
return dictionary_b();
default:
throw (new Exception("文件結構錯誤."));
}
}
string string_b()
{
int length = (int)extraction_integer();
match(':');
if (curKey != "pieces")
{
UTF8Encoding utf8Encoding = new UTF8Encoding();
curIndex += length;
return utf8Encoding.GetString(bencodeArray, curIndex-length, length);
}
else
{
StringBuilder hashSB = new StringBuilder();
for (int i = 0; i != length; ++i)
hashSB.Append(bencodeArray[curIndex++].ToString("X2"));
return hashSB.ToString();
}
}
long integer_b()
{
match('i');
long i = extraction_integer();
match('e');
return i;
}
List<object> list_b()
{
match('l');
List</object><object> list = new List</object><object>();
while (bencodeArray[curIndex] != 'e')
list.Add(scan());
match('e');
return list;
}
Dictionary<string ,object> dictionary_b()
{
match('d');
Dictionary</string><string , object> dic = new Dictionary</string><string , object>();
while (bencodeArray[curIndex] != 'e')
{
curKey = string_b();
dic[curKey] = scan();
curKey = "";
}
match('e');
return dic;
}
long extraction_integer()
{
StringBuilder intSB = new StringBuilder();
while ('0'< =bencodeArray[curIndex] && bencodeArray[curIndex] <= '9' || bencodeArray[curIndex]=='-')
intSB.Append((char)bencodeArray[curIndex++]);
return long.Parse(intSB.ToString());
}
void match(char c)
{
if (bencodeArray[curIndex++] != c)
throw (new Exception("文件結構錯誤."));
}
List<FileInTorrent> getFiles()
{
Dictionary</string><string , object> info = rootDictionary["info"] as Dictionary</string><string , object>;
if (info.ContainsKey("files"))
{
List<fileintorrent> files = new List</fileintorrent><fileintorrent>();
List<object> fileList = info["files"] as List</object><object>;
foreach (Dictionary<string , object> file in fileList)
{
List<object> pathList = file["path"] as List</object><object>;
string path = "";
foreach (string s in pathList)
path += "\\"+s;
files.Add(new FileInTorrent(path, (long)file["length"]));
}
return files;
}
else
{
List<fileintorrent> files = new List</fileintorrent><fileintorrent>();
files.Add(new FileInTorrent(info["name"] as string, (long)info["length"]));
return files;
}
}
public string Announce
{
get { return rootDictionary["announce"] as string; }
}
public string CreatedBy
{
get { return rootDictionary["created by"] as string; }
}
public DateTime CreationDate
{
get { return new DateTime(1970, 1, 1, 0, 0, 0).AddSeconds((long)rootDictionary["creation date"]); }
}
public string Encoding
{
get { return rootDictionary["encoding"] as string; }
}
public long PieceLength
{
get { return (long)(rootDictionary["info"] as Dictionary<string ,object>)["piece length"]; }
}
public string Pieces
{
get { return (string)(rootDictionary["info"] as Dictionary</string><string , object>)["pieces"]; }
}
public List<fileintorrent> Files
{
get { return files; }
}
public bool Private
{
get
{
if ((rootDictionary["info"] as Dictionary<string ,object>).ContainsKey("private"))
return (long)(rootDictionary["info"] as Dictionary</string><string , object>)["private"] == 1;
else
return false;
}
}
string filename;
int curIndex;
string curKey;
byte[] bencodeArray;
Dictionary</string><string , object> rootDictionary;
List<fileintorrent> files;
}
</fileintorrent></string></fileintorrent></string></fileintorrent></object></string></object></fileintorrent></string></object></string>
阅读全文…
近期评论