473,830 Members | 2,207 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to cast int to short

ad
I have a custom function which accept short as parameter.
for example:

public void myFun(short myShor)
{...}

Now I have a integer (int i), I want to take as the aprameter of myFun,
How can I cast i to short ?
Feb 15 '06 #1
4 30696
ad <fl****@wfes.tc c.edu.tw> wrote:
I have a custom function which accept short as parameter.
for example:

public void myFun(short myShor)
{...}

Now I have a integer (int i), I want to take as the aprameter of myFun,
How can I cast i to short ?


myFun ((short)i);

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Feb 15 '06 #2
Jon Skeet [C# MVP] wrote:
ad <fl****@wfes.tc c.edu.tw> wrote:
public void myFun(short myShor) {...}

Now I have a integer (int i), I want to take as the aprameter of
myFun, How can I cast i to short ?


myFun ((short)i);


Note that, by default, C# checks for integer overflow when performing a cast
in this obvious way. If you prefer to truncate the most significant bits,
you either need to remove them beforehand using a bitmask or perform the
cast inside an "unchecked {}" block. You can read more about unchecked here:

http://msdn.microsoft.com/library/de...funchecked.asp

--
Derrick Coetzee, MCAD, MSFT (Speech Server)
This posting is provided "AS IS" with no warranties, and confers no
rights.
Feb 16 '06 #3
Derrick Coetzee [MSFT] <dc******@onlin e.microsoft.com > wrote:
myFun ((short)i);


Note that, by default, C# checks for integer overflow when performing a cast
in this obvious way. If you prefer to truncate the most significant bits,
you either need to remove them beforehand using a bitmask or perform the
cast inside an "unchecked {}" block. You can read more about unchecked here:

http://msdn.microsoft.com/library/de...ary/en-us/csre
f/html/vclrfunchecked. asp


No, by default C# *doesn't* check for overflow, except for compile-time
constant expressions. So:

// Doesn't compile
uint x = (uint)-1;
// Does compile
uint x = unchecked((uint )-1);

// Compiles and runs without exception
int y = -1;
uint x = (uint)y;

// Compiles but throws an exception
int y = -1;
uint x = checked((uint)y );

Note that the default behaviour can also be controlled by a compiler
switch or project setting.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Feb 16 '06 #4
Jon Skeet [C# MVP] wrote:
Derrick Coetzee [MSFT] <dc******@onlin e.microsoft.com > wrote:
myFun ((short)i);


Note that, by default, C# checks for integer overflow when
performing a cast in this obvious way. [...]


No, by default C# *doesn't* check for overflow, except for
compile-time constant expressions.


Sorry, my mistake - I'm used to this option being on. I do personally
recommend that the /checked option (Build->Advanced->Check for arithmetic
overflow/underflow) is always used, as this can help to find bugs and
prevent potential security issues, as well as provide conceptual safety
guarantees (and I think it should be on by default). If profiling reveals
that they're slowing down a bottleneck, or if you want the C behaviour of
arithmetic mod 2^word size, you can always wrap the relevant code in
unchecked { }. Thanks for the correction, Jon.
--
Derrick Coetzee, MCAD, MSFT (Speech Server)
This posting is provided "AS IS" with no warranties, and confers no
rights.
Feb 16 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
4902
by: Michael Baehr | last post by:
I recently upgraded my Arch Linux system to GCC 3.4, and found out that a previously accepted behavior (cast-as-lvalue) is now marked as deprecated, and will cease to function in GCC 3.5. This has caused several builds to break, most notably elfutils. Presumably this behavior is not part of the C standard and it is thus being excised like many other nonstandard GCC extensions. Regardless, my question is not about the specifics or...
6
1665
by: JS | last post by:
On this page under "Malloc": http://www.le.ac.uk/cc/tutorials/c/ccccstrc.html I found this: ptr = (*int) malloc(sizeof(int)*N)
1
3615
by: C Learner | last post by:
Hi, I'm new to C#. I have a C++ program and need to develop it in C# now. In C++ Program: typedef struct A_T { char id; DWORD status; } AStruct AStruct rcd; SYSTEMTIME st;
7
12039
by: simon | last post by:
I declare variable as int16: int16 hourS; then I open dataReader and set the variable: hourS=rdr.getInt16(1); but I get an error when I start the page:
0
1568
by: BobTheHacker | last post by:
I have a c# class library that I call to centralize some code amongst projects. It returns an arraylist back to the calling function that contains class data. Anyway when I call it I can receive it as an object and the data looks fine. However when I do the type casting I get the above error. Any ideas. Below is the code. At the bottom you can see the comment on the cast that blows. I have even tried it without using the Object*. I just...
6
527
by: Jack | last post by:
Is it possible to cast a 4-byte data type (e.g. an unsigned int) to a 4-byte struct? Sometimes the HIWORD and LOWORD of a 4-byte value contain information independent of each other. Is there a direct way to perform this cast? If not, is there way in C++ to do it? For example, I would like my function test() to work the way it is coded below. It produces a compiler error though: #include <pshpack2.h// 16-bit padding
9
12951
by: Hamish M | last post by:
Hi I am interested in opinions on this topic. I have heard that a suffix is not a good solution and type casts are much better for example. ----------------------------------------------------------------- #define MAX_UWORD (T_UWORD)65535
4
2837
by: Terry | last post by:
I have a TextBox with a date such as 15/01/2006 which I want to cast into a variable as a short date 15/01/06, also I need to cast a time such as 07:30 A.M. into a variable as a short time. What is the best syntax for this please? Regards
8
5503
by: ManicQin | last post by:
Hi, I've browsed the STL code a bit and stumble upon the next line (in the operator << overload of both long and short outputs - the line is for checking does the input is a manipulator) long _Tmp = (_Bfl == ios_base::oct || _Bfl == ios_base::hex) ? (long)(unsigned short)_Val //<-This Line : (long)_Val; Is there any profound reason why they "Double" casting the _Val? Thanks.
0
9641
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10477
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10522
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10197
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9310
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6944
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5615
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4408
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3072
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.